Search Results

Search found 1308 results on 53 pages for 'rectangle'.

Page 1/53 | 1 2 3 4 5 6 7 8 9 10 11 12  | Next Page >

  • Reacting to rectangle on rectangle collisions

    - by mcjohnalds45
    I don't know how to react to collisions between two axis aligned rectangles that have x, y, width and height values (x and y are from the centre of the box) to make them simply not overlap. I figured I'd just make them move away from each other depending on how far they intersect in the opposite direction (left, right, up or down) of where they collided. If I check for collisions only on the x axis or only on the y axis it works fine, but when checking for both collisions crazy stuff happens. This code executes when the first box collides with the second. It's in lua but feel free to answer in anything that isn't to too counter-intuitive. if box1.x < box2.x then box1.x = box1.x + box2.x - box1.x - (box1.width / 2) - (box2.width / 2) end if box1.x > box2.x then box1.x = box1.x - (box1.x - box2.x - (box1.width / 2) - (box2.width / 2)) end if box1.y < box2.y then box1.y = box1.y + box2.y - box1.y - (box1.height / 2) - (box2.height / 2) end if box1.y > box2.y then box1.y = box1.y - (box1.y - box2.y - (box1.height / 2) - (box2.height / 2)) end

    Read the article

  • Draw Rectangle To All Dimensions of Image

    - by opiop65
    I have some rudimentary collision code: public class Collision { static boolean isColliding = false; static Rectangle player; static Rectangle female; public static void collision(){ Rectangle player = Game.Playerbounds(); Rectangle female = Game.Femalebounds(); if(player.intersects(female)){ isColliding = true; }else{ isColliding = false; } } } And this is the rectangle code: public static Rectangle Playerbounds() { return(new Rectangle(posX, posY, 25, 25)); } public static Rectangle Femalebounds() { return(new Rectangle(femaleX, femaleY, 25, 25)); } My InputHandling class: public static void movePlayer(GameContainer gc, int delta){ Input input = gc.getInput(); if(input.isKeyDown(input.KEY_W)){ Game.posY -= walkSpeed * delta; walkUp = true; if(Collision.isColliding == true){ Game.posY += walkSpeed * delta; } } if(input.isKeyDown(input.KEY_S)){ Game.posY += walkSpeed * delta; walkDown = true; if(Collision.isColliding == true){ Game.posY -= walkSpeed * delta; } } if(input.isKeyDown(input.KEY_D)){ Game.posX += walkSpeed * delta; walkRight = true; if(Collision.isColliding == true){ Game.posX -= walkSpeed * delta; } } if(input.isKeyDown(input.KEY_A)){ Game.posX -= walkSpeed * delta; walkLeft = true; if(Collision.isColliding == true){ Game.posX += walkSpeed * delta; } } } The code works partially. Only the right and top side of the images collide. How do I correct the rectangle so it will draw on all sides? Thanks for any suggestions!

    Read the article

  • XNA Level Select Menu

    - by user29901
    I'll try to explain this the best I can. I'm trying to create a level select menu for a game I'm making. The menu is basically a group of blocks numbered 1-16, similar to something like the Angry Birds menu. What I've done is created a cursor, basically just an outline to surround a block, that the user can move to select what level they want to play. What I want it do is move from block to block instead of simply moving around on the X and Y axes as it does now. So my question is, how can I get the cursor (highLight in the below code) to move from block to block(destinationRectangle1 etc. in the code)? /// Field for the "cursor" Vector2 highLightPos = new Vector2(400, 200); ///This is the Update code KeyboardState keyBoardState = Keyboard.GetState(); if (keyBoardState.IsKeyDown(Keys.Up)) highLightPos.Y--; if (keyBoardState.IsKeyDown(Keys.Down)) highLightPos.Y++; if (keyBoardState.IsKeyDown(Keys.Right)) highLightPos.X++; if (keyBoardState.IsKeyDown(Keys.Left)) highLightPos.X--; /// This is the draw code SpriteBatch spriteBatch = ScreenManager.SpriteBatch; Rectangle screenRectangle = new Rectangle(0, 0, 1280, 720); Rectangle destinationRectangle1 = new Rectangle(400, 200, 64, 64); Rectangle frameRectangle1 = new Rectangle(0, 0, 64, 64); Rectangle destinationRectangle2 = new Rectangle(500, 200, 64, 64); Rectangle frameRectangle2 = new Rectangle(64, 0, 64, 64); Rectangle destinationRectangle3 = new Rectangle(600, 200, 64, 64); Rectangle frameRectangle3 = new Rectangle(128, 0, 64, 64); Rectangle destinationRectangle4 = new Rectangle(700, 200, 64, 64); Rectangle frameRectangle4 = new Rectangle(192, 0, 64, 64); Rectangle destinationRectangle5 = new Rectangle(800, 200, 64, 64); Rectangle frameRectangle5 = new Rectangle(256, 0, 64, 64); Rectangle destinationRectangle6 = new Rectangle(400, 300, 64, 64); Rectangle frameRectangle6 = new Rectangle(320, 0, 64, 64); Rectangle destinationRectangle7 = new Rectangle(500, 300, 64, 64); Rectangle frameRectangle7 = new Rectangle(384, 0, 64, 64); Rectangle destinationRectangle8 = new Rectangle(600, 300, 64, 64); Rectangle frameRectangle8 = new Rectangle(448, 0, 64, 64); Rectangle destinationRectangle9 = new Rectangle(700, 300, 64, 64); Rectangle frameRectangle9 = new Rectangle(0, 64, 64, 64); Rectangle destinationRectangle10 = new Rectangle(800, 300, 64, 64); Rectangle frameRectangle10 = new Rectangle(64, 64, 64, 64); Rectangle destinationRectangle11 = new Rectangle(400, 400, 64, 64); Rectangle frameRectangle11 = new Rectangle(128, 64, 64, 64); Rectangle destinationRectangle12 = new Rectangle(500, 400, 64, 64); Rectangle frameRectangle12 = new Rectangle(192, 64, 64, 64); Rectangle destinationRectangle13 = new Rectangle(600, 400, 64, 64); Rectangle frameRectangle13 = new Rectangle(256, 64, 64, 64); Rectangle destinationRectangle14 = new Rectangle(700, 400, 64, 64); Rectangle frameRectangle14 = new Rectangle(320, 64, 64, 64); Rectangle destinationRectangle15 = new Rectangle(800, 400, 64, 64); Rectangle frameRectangle15 = new Rectangle(384, 64, 64, 64); Rectangle destinationRectangle16 = new Rectangle(600, 500, 64, 64); Rectangle frameRectangle16 = new Rectangle(448, 64, 64, 64); spriteBatch.Begin(); spriteBatch.Draw(forestBG, screenRectangle, Color.White); spriteBatch.Draw(highLight, highLightPos, Color.White); spriteBatch.Draw(levelSelectTiles, destinationRectangle1, frameRectangle1, Color.White); spriteBatch.Draw(levelSelectTiles, destinationRectangle2, frameRectangle2, Color.White); spriteBatch.Draw(levelSelectTiles, destinationRectangle3, frameRectangle3, Color.White); spriteBatch.Draw(levelSelectTiles, destinationRectangle4, frameRectangle4, Color.White); spriteBatch.Draw(levelSelectTiles, destinationRectangle5, frameRectangle5, Color.White); spriteBatch.Draw(levelSelectTiles, destinationRectangle6, frameRectangle6, Color.White); spriteBatch.Draw(levelSelectTiles, destinationRectangle7, frameRectangle7, Color.White); spriteBatch.Draw(levelSelectTiles, destinationRectangle8, frameRectangle8, Color.White); spriteBatch.Draw(levelSelectTiles, destinationRectangle9, frameRectangle9, Color.White); spriteBatch.Draw(levelSelectTiles, destinationRectangle10, frameRectangle10, Color.White); spriteBatch.Draw(levelSelectTiles, destinationRectangle11, frameRectangle11, Color.White); spriteBatch.Draw(levelSelectTiles, destinationRectangle12, frameRectangle12, Color.White); spriteBatch.Draw(levelSelectTiles, destinationRectangle13, frameRectangle13, Color.White); spriteBatch.Draw(levelSelectTiles, destinationRectangle14, frameRectangle14, Color.White); spriteBatch.Draw(levelSelectTiles, destinationRectangle15, frameRectangle15, Color.White); spriteBatch.Draw(levelSelectTiles, destinationRectangle16, frameRectangle16, Color.White); spriteBatch.End(); PS, I'm aware that this code is probably inefficient, cumbersome or that there's a better way to draw parts of a tile sheet. Any suggestions would be appreciated.

    Read the article

  • Create a rectangle struct to be rotated and have a .Intersects() function

    - by MintyAnt
    In my XNA program, I am trying to swing a sword. The sword starts at an angle of 180 degrees, then rotates (clockwise) to an angle of 90 degrees. The Rectangle struct that XNA provides, Rectangle mAttackBox = new Rectangle(int x, int y, int width, int height); However, this struct has two problems: Holds position and size in Integers, not Floats Cannot be rotated I was hoping someone could help me in either telling me that i'm wrong and the Rectangle can be used for both these methods, or can lead me down the right path for rotating a rectangle. I know how to create a Struct. I believe that I can make methods like classes. I can determine the 4 vertices of a 2D rectangle by calculating out the x,y of the other 3 given the length, width. I'm sure theres a Matrix class I can use to multiply each point against a Rotation matrix. But once i have my 4 vertices, I got two other problems: - How do I test other rectangles against it? How does .Intersects() work for the rectangle struct? - Is this even the fastest way to do it? I'd be constantly doing matrix multiplication, wouldnt that slow things down?

    Read the article

  • Creating Rectangle-based buttons with OnClick events

    - by Djentleman
    As the title implies, I want a Button class with an OnClick event handler. It should fire off connected events when it is clicked. This is as far as I've made it: public class Button { public event EventHandler OnClick; public Rectangle Rec { get; set; } public string Text { get; set; } public Button(Rectangle rec, string text) { this.Rec = rec; this.Text = text; } } I have no clue what I'm doing with regards to events. I know how to use them but creating them myself is another matter entirely. I've also made buttons without using events that work on a case-by-case basis. So basically, I want to be able to attach methods to the OnClick EventHandler that will fire when the Button is clicked (i.e., the mouse intersects Rec and the left mouse button is clicked).

    Read the article

  • Fast rectangle to rectangle intersection

    - by Jeremy Rudd
    What's a fast way to test if 2 rectangles are intersecting? A search on the internet came up with this one-liner (WOOT!), but I don't understand how to write it in Javascript, it seems to be written in an ancient form of C++. struct { LONG left; LONG top; LONG right; LONG bottom; } RECT; bool IntersectRect(const RECT * r1, const RECT * r2) { return ! ( r2->left > r1->right || r2->right left || r2->top > r1->bottom || r2->bottom top ); }

    Read the article

  • Java 2D Rectangle Collision? [on hold]

    - by Andreas Elia
    I am just wanting to know of another (longer OR shorter) way of getting 100% effective collisions on a 2D plat-former. The current collision system that is in place works from coords on the level and does not always work reliably. Thank you in advance for any help/support. The current system draws a rectangle and is checking to see if any two points collide. From testing, the system can sometimes "glitch" and allow the player to collide into walls etc. Player Class http://pastebin.com/2zE8vz8R Main Class http://pastebin.com/A6Utb3ti

    Read the article

  • Android Java rectangle collision detection not working

    - by Charlton Santana
    I had been hard coding a collision detection system which was buggy. Then I came across using rectangles for collsion detection. So I put it all in and it does not work, I put a log in and it never logged. Note to Java programmers who are not Android programers: Android uses the word Rect instead of Rectangle. Code for Block.java: public Rect getBounds(){ return new Rect (this.x, this.y, 10, 20); } Code for Sprite.java: public Rect getBounds(){ return new Rect (this.x, this.y, 20, 20); } Code for MainGame.java: for(Block block : BLOCKS) { block.draw(canvas); block.rigidbody(); Rect spriter = sprite.getBounds(); Rect blockr = block.getBounds(); if(spriter.intersect(blockr)){ showgameover = 1; Log.d(TAG, "Game Over"); } } Is anyone able to help?

    Read the article

  • Drawing a continuous rectangle

    - by JAYMIN
    Hi..i m currently working on visual c++ 2008 express edition.. in my project i have a picturebox which contains an image, now i have to draw a rectangle to enaable the user to select a part of the image.. I have used the "MouseDown" event of the picturebox and the below code to draw a rectangle: Void pictureBox1_MouseDown(System::Object^ sender, Windows::Forms::MouseEventArgs^ e) { Graphics^ g = pictureBox1-CreateGraphics(); Pen^ pen = gcnew Pen(Color::Blue); g-DrawRectangle( pen , e-X ,e-Y,width,ht); } now in the "DrawRectangle" the arguments "width" and "ht" are static, so the above code results in the drawing of a rectangle at the point where the user presses the mouse button on the image in picturebox... i want to allow the user to be able to drag the cursor and draw a rectangle of size that he wishes to.. Plz help me on this.. Thanx..

    Read the article

  • Find Upper Right Point of Rotated Rectangle in AS3 (Flex)

    - by coltech
    I have a rectangle of any arbitrary width and height. I know X,Y, width, and height. How do I solve the upper right hand coordinates when the rectangle is rotated N degrees? I realized if it were axis aligned I would simply solve for (x,y+width). Unforunatly this doesn't hold true when I apply a transform matrix on the rectangle to rotate it around its center.

    Read the article

  • Collision Detection - Java - Rectangle

    - by Trizicus
    I would like to know if this is a good idea that conforms to best practices that does not lead to obscenely confusing code or major performance hit(s): Make my own Collision detection class that extends Rectangle class. Then when instantiating that object doing something such as Collision col = new Rectangle(); <- Should I do that or is that something that should be avoided? I am aware that I 'can' but should I? I want to extend Rectangle class because of the contains() and intersects() methods; should I be doing that or should I be doing something else for 2D collision detection in Java?

    Read the article

  • Rectangle Rotation in Python/Pygame

    - by mramazingguy
    Hey I'm trying to rotate a rectangle around its center and when I try to rotate the rectangle, it moves up and to the left at the same time. Does anyone have any ideas on how to fix this? def rotatePoint(self, angle, point, origin): sinT = sin(radians(angle)) cosT = cos(radians(angle)) return (origin[0] + (cosT * (point[0] - origin[0]) - sinT * (point[1] - origin[1])), origin[1] + (sinT * (point[0] - origin[0]) + cosT * (point[1] - origin[1]))) def rotateRect(self, degrees): center = (self.collideRect.centerx, self.collideRect.centery) self.collideRect.topleft = self.rotatePoint(degrees, self.collideRect.topleft, center) self.collideRect.topright = self.rotatePoint(degrees, self.collideRect.topright, center) self.collideRect.bottomleft = self.rotatePoint(degrees, self.collideRect.bottomleft, center) self.collideRect.bottomright = self.rotatePoint(degrees, self.collideRect.bottomright, center)

    Read the article

  • .NET Rectangle Off By 1

    - by roygbiv
    After working with the .NET GDI+ Rectangle object, I've noticed that if I create a rectangle that is X:0 * Y:0 * Width:100 * Height:100, the Right and Bottom properties are set to 100, 100. Shouldn't this be 99, 99? 0 - 99 is 100 pixels. 0 - 100 is 101 pixels. FWIW, the documentation does say the right is computed by x + width and the bottom is y + height, but is that correct? Perhaps "correct" doesn't matter here as long it's consistent? All I know is that it is somewhat (read... very) annoying!

    Read the article

  • Draw Rectangle with XNA

    - by mazzzzz
    Hey guys, I was working on game, and wanted to highlight a spot on the screen when something happens, I created a class to do this for me, and found a bit of code to draw the rectangle static private Texture2D CreateRectangle(int width, int height, Color colori) { Texture2D rectangleTexture = new Texture2D(game.GraphicsDevice, width, height, 1, TextureUsage.None, SurfaceFormat.Color);// create the rectangle texture, ,but it will have no color! lets fix that Color[] color = new Color[width * height];//set the color to the amount of pixels in the textures for (int i = 0; i < color.Length; i++)//loop through all the colors setting them to whatever values we want { color[i] = colori; } rectangleTexture.SetData(color);//set the color data on the texture return rectangleTexture;//return the texture } Problem is that the code above is called every update, (60 times a second), and it was not written with optimization in mind, I have no clue how else to write a code to do this though. It needs to be extremely fast (the code above freezes the game, which has only skeleton code right now).. Any suggestions. Note: Any new code would be great (WireFrame/Fill are both fine). I would like to be able to specify color. Something to point in the right direction would be great, Thanks, Max

    Read the article

  • How to select a rectangle from List<Rectangle[]> with Linq

    - by dboarman
    I have a list of DrawObject[]. Each DrawObject has a Rectangle property. Here is my event: List<Canvas.DrawObject[]> matrix; void Control_MouseMove ( object sender, MouseEventArgs e ) { IEnumerable<Canvas.DrawObject> tile = Enumerable.Range( 0, matrix.Capacity - 1) .Where(row => Enumerable.Range(0, matrix[row].Length -1) .Where(column => this[column, row].Rectangle.Contains(e.Location))) .????; } I am not sure exactly what my final select command should be in place of the "????". Also, I was getting an error: cannot convert IEnumerable to bool. I've read several questions about performing a linq query on a list of arrays, but I can't quite get what is going wrong with this. Any help? Edit Apologies for not being clear in my intentions with the implementation. I intend to select the DrawObject that currently contains the mouse location.

    Read the article

  • circle - rectangle collision in 2D, most efficient way

    - by john smith
    Suppose I have a circle intersecting a rectangle, what is ideally the least cpu intensive way between the two? method A calculate rectangle boundaries loop through all points of the circle and, for each of those, check if inside the rect. method B calculate rectangle boundaries check where the center of the circle is, compared to the rectangle make 9 switch/case statements for the following positions: top, bottom, left, right top left, top right, bottom left, bottom right inside rectangle check only one distance using the circle's radius depending on where the circle happens t be. I know there are other ways that are definitely better than these two, and if could point me a link to them, would be great but, exactly between those two, which one would you consider to be better, regarding both performance and quality/precision? Thanks in advance.

    Read the article

  • Get collision details from Rectangle.Intersects()

    - by Daniel Ribeiro
    I have a Breakout game in which, at some point, I detect the collision between the ball and the paddle with something like this: // Ball class rectangle.Intersects(paddle.Rectangle); Is there any way I can get the exact coordinates of the collision, or any details about it, with the current XNA API? I thought of doing some basic calculations, such as comparing the exact coordinates of each object on the moment of the collision. It would look something like this: // Ball class if((rectangle.X - paddle.Rectangle.X) < (paddle.Rectangle.Width / 2)) // Collision happened on the left side else // Collision happened on the right side But I'm not sure this is the correct way to do it. Do you guys have any tips on maybe an engine I might have to use to achieve that? Or even good coding practices using this method?

    Read the article

  • how does the rectangle bounds (x,y,width,height) in libgdx work

    - by JG22
    I cant work out how to use the rectangle bounds in libgdx I am currently using the superJumper example and have 2or 3 examples with that are pause Bounds = new Rectangle(320 - 64, 480 - 64, 64, 64); this is the pause button in the top right corner resume Bounds = new Rectangle(160 - 96, 240, 192, 36); this is a rectangle resume button in the middle of the page in the menu that comes up when the pause button is pressed. basically my question is aimed at the 360 -64 and 160 -96 because I don't know why this is used I need to create a rectangle that covers the left side of the screen and the same on the right because I want to create a on screen buttons, I have already created the does for these buttons and I have managed to get them to work but I can move the rectangles to where I want. Thank you If you can help

    Read the article

  • C#/.NET Little Wonders: Use Cast() and TypeOf() to Change Sequence Type

    - by James Michael Hare
    Once again, in this series of posts I look at the parts of the .NET Framework that may seem trivial, but can help improve your code by making it easier to write and maintain. The index of all my past little wonders posts can be found here. We’ve seen how the Select() extension method lets you project a sequence from one type to a new type which is handy for getting just parts of items, or building new items.  But what happens when the items in the sequence are already the type you want, but the sequence itself is typed to an interface or super-type instead of the sub-type you need? For example, you may have a sequence of Rectangle stored in an IEnumerable<Shape> and want to consider it an IEnumerable<Rectangle> sequence instead.  Today we’ll look at two handy extension methods, Cast<TResult>() and OfType<TResult>() which help you with this task. Cast<TResult>() – Attempt to cast all items to type TResult So, the first thing we can do would be to attempt to create a sequence of TResult from every item in the source sequence.  Typically we’d do this if we had an IEnumerable<T> where we knew that every item was actually a TResult where TResult inherits/implements T. For example, assume the typical Shape example classes: 1: // abstract base class 2: public abstract class Shape { } 3:  4: // a basic rectangle 5: public class Rectangle : Shape 6: { 7: public int Widtgh { get; set; } 8: public int Height { get; set; } 9: } And let’s assume we have a sequence of Shape where every Shape is a Rectangle… 1: var shapes = new List<Shape> 2: { 3: new Rectangle { Width = 3, Height = 5 }, 4: new Rectangle { Width = 10, Height = 13 }, 5: // ... 6: }; To get the sequence of Shape as a sequence of Rectangle, of course, we could use a Select() clause, such as: 1: // select each Shape, cast it to Rectangle 2: var rectangles = shapes 3: .Select(s => (Rectangle)s) 4: .ToList(); But that’s a bit verbose, and fortunately there is already a facility built in and ready to use in the form of the Cast<TResult>() extension method: 1: // cast each item to Rectangle and store in a List<Rectangle> 2: var rectangles = shapes 3: .Cast<Rectangle>() 4: .ToList(); However, we should note that if anything in the list cannot be cast to a Rectangle, you will get an InvalidCastException thrown at runtime.  Thus, if our Shape sequence had a Circle in it, the call to Cast<Rectangle>() would have failed.  As such, you should only do this when you are reasonably sure of what the sequence actually contains (or are willing to handle an exception if you’re wrong). Another handy use of Cast<TResult>() is using it to convert an IEnumerable to an IEnumerable<T>.  If you look at the signature, you’ll see that the Cast<TResult>() extension method actually extends the older, object-based IEnumerable interface instead of the newer, generic IEnumerable<T>.  This is your gateway method for being able to use LINQ on older, non-generic sequences.  For example, consider the following: 1: // the older, non-generic collections are sequence of object 2: var shapes = new ArrayList 3: { 4: new Rectangle { Width = 3, Height = 13 }, 5: new Rectangle { Width = 10, Height = 20 }, 6: // ... 7: }; Since this is an older, object based collection, we cannot use the LINQ extension methods on it directly.  For example, if I wanted to query the Shape sequence for only those Rectangles whose Width is > 5, I can’t do this: 1: // compiler error, Where() operates on IEnumerable<T>, not IEnumerable 2: var bigRectangles = shapes.Where(r => r.Width > 5); However, I can use Cast<Rectangle>() to treat my ArrayList as an IEnumerable<Rectangle> and then do the query! 1: // ah, that’s better! 2: var bigRectangles = shapes.Cast<Rectangle>().Where(r => r.Width > 5); Or, if you prefer, in LINQ query expression syntax: 1: var bigRectangles = from s in shapes.Cast<Rectangle>() 2: where s.Width > 5 3: select s; One quick warning: Cast<TResult>() only attempts to cast, it won’t perform a cast conversion.  That is, consider this: 1: var intList = new List<int> { 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89 }; 2:  3: // casting ints to longs, this should work, right? 4: var asLong = intList.Cast<long>().ToList(); Will the code above work?  No, you’ll get a InvalidCastException. Remember that Cast<TResult>() is an extension of IEnumerable, thus it is a sequence of object, which means that it will box every int as an object as it enumerates over it, and there is no cast conversion from object to long, and thus the cast fails.  In other words, a cast from int to long will succeed because there is a conversion from int to long.  But a cast from int to object to long will not, because you can only unbox an item by casting it to its exact type. For more information on why cast-converting boxed values doesn’t work, see this post on The Dangers of Casting Boxed Values (here). OfType<TResult>() – Filter sequence to only items of type TResult So, we’ve seen how we can use Cast<TResult>() to change the type of our sequence, when we expect all the items of the sequence to be of a specific type.  But what do we do when a sequence contains many different types, and we are only concerned with a subset of a given type? For example, what if a sequence of Shape contains Rectangle and Circle instances, and we just want to select all of the Rectangle instances?  Well, let’s say we had this sequence of Shape: 1: var shapes = new List<Shape> 2: { 3: new Rectangle { Width = 3, Height = 5 }, 4: new Rectangle { Width = 10, Height = 13 }, 5: new Circle { Radius = 10 }, 6: new Square { Side = 13 }, 7: // ... 8: }; Well, we could get the rectangles using Select(), like: 1: var onlyRectangles = shapes.Where(s => s is Rectangle).ToList(); But fortunately, an easier way has already been written for us in the form of the OfType<T>() extension method: 1: // returns only a sequence of the shapes that are Rectangles 2: var onlyRectangles = shapes.OfType<Rectangle>().ToList(); Now we have a sequence of only the Rectangles in the original sequence, we can also use this to chain other queries that depend on Rectangles, such as: 1: // select only Rectangles, then filter to only those more than 2: // 5 units wide... 3: var onlyBigRectangles = shapes.OfType<Rectangle>() 4: .Where(r => r.Width > 5) 5: .ToList(); The OfType<Rectangle>() will filter the sequence to only the items that are of type Rectangle (or a subclass of it), and that results in an IEnumerable<Rectangle>, we can then apply the other LINQ extension methods to query that list further. Just as Cast<TResult>() is an extension method on IEnumerable (and not IEnumerable<T>), the same is true for OfType<T>().  This means that you can use OfType<TResult>() on object-based collections as well. For example, given an ArrayList containing Shapes, as below: 1: // object-based collections are a sequence of object 2: var shapes = new ArrayList 3: { 4: new Rectangle { Width = 3, Height = 5 }, 5: new Rectangle { Width = 10, Height = 13 }, 6: new Circle { Radius = 10 }, 7: new Square { Side = 13 }, 8: // ... 9: }; We can use OfType<Rectangle> to filter the sequence to only Rectangle items (and subclasses), and then chain other LINQ expressions, since we will then be of type IEnumerable<Rectangle>: 1: // OfType() converts the sequence of object to a new sequence 2: // containing only Rectangle or sub-types of Rectangle. 3: var onlyBigRectangles = shapes.OfType<Rectangle>() 4: .Where(r => r.Width > 5) 5: .ToList(); Summary So now we’ve seen two different ways to get a sequence of a superclass or interface down to a more specific sequence of a subclass or implementation.  The Cast<TResult>() method casts every item in the source sequence to type TResult, and the OfType<TResult>() method selects only those items in the source sequence that are of type TResult. You can use these to downcast sequences, or adapt older types and sequences that only implement IEnumerable (such as DataTable, ArrayList, etc.). Technorati Tags: C#,CSharp,.NET,LINQ,Little Wonders,TypeOf,Cast,IEnumerable<T>

    Read the article

  • Algorithm for finding a rectangle constrained to its parent

    - by Milo
    Basically what I want to do is illustrated here: I start with A and B, then B is conformed to A to create C. The idea is, given TLBR rectangles A, B, make C I also need to know if it produces an empty rectangle (B outside of A case). I tried this but it just isn't doing what I want: if(clipRect.getLeft() > rect.getLeft()) L = clipRect.getLeft(); else L = rect.getLeft(); if(clipRect.getRight() < rect.getRight()) R = clipRect.getRight(); else R = rect.getRight(); if(clipRect.getBottom() > rect.getBottom()) B = clipRect.getBottom(); else B = rect.getBottom(); if(clipRect.getTop() < rect.getTop()) T = clipRect.getTop(); else T = rect.getTop(); if(L < R && B < T) { clipRect = AguiRectangle(0,0,0,0); } else { clipRect = AguiRectangle::fromTLBR(T,L,B,R); } Thanks

    Read the article

  • Rope Colliding with a Rectangle

    - by Colton
    I have my rope, and I have my rectangles. The rope is similar to the implementation found here: http://nehe.gamedev.net/tutorial/rope_physics/17006/ Now, I want to make the rope properly collide with the rectangle such that the rope will not pass through a rectangle, and wrap around the rectangle and all that good stuff. Currently, I have it set so no rope node can pass through a rect (successfully), however, this means a rope segment can still pass through a block. Ex: So the question is, what can I do to fix this? What I have tried: I create a rectangle between two nodes of a rope, calculate rotation between the nodes, and get myself a transformed rectangle. I can successfully detect a collision between rope segments and a (non-transformed) rectangle. Create a new node or pivot point around the corner of the block, and rearrange nodes to point to the corner node. Trouble is determining what corner the rope segment is passing through. And then the current rope setup goes wonky (based on verlet integration, so a sudden change in position causes the rope to wiggle like a seismograph during a magnitude 8 earth quake.) Among other issues that might be solvable, but its turning into a case by case thing, which doesn't seem right. I think the best answer here would just be a link to a tutorial (I simply can't find any, most lead to box2D or farseer, but I want to at least learn how it works before I hide behind an engine).

    Read the article

  • Can this rectangle to rectangle intersection code still work?

    - by Jeremy Rudd
    I was looking for a fast performing code to test if 2 rectangles are intersecting. A search on the internet came up with this one-liner (WOOT!), but I don't understand how to write it in Javascript, it seems to be written in an ancient form of C++. Can this thing still work? Can you make it work? struct { LONG left; LONG top; LONG right; LONG bottom; } RECT; bool IntersectRect(const RECT * r1, const RECT * r2) { return ! ( r2->left > r1->right || r2->right left || r2->top > r1->bottom || r2->bottom top ); }

    Read the article

  • Triangle - Rectangle Intersection in 2D

    - by Kevin Boyd
    I had previously asked this for 3D but now I changed my strategy and would like to do the intersection in 2D. The Rectangle is axis aligned and will always be in a fixed position, and has a constant shape and size, basically I want to clip the red areas of the triangles that extend outside the bounds of the rectangle The triangles could be in any position, shape or size, I my code I have a loop where I check the triangles one by one however I am still clueless about the math. I have identified 5 cases of triangle rectangle intersection as shown here. How do I find the intersection points of the triangle and the rectangle?

    Read the article

  • 2D Rectangle Collision Response with Multiple Rectangles

    - by Justin Skiles
    Similar to: Collision rectangle response I have a level made up of tiles where the edges of the level are made up of collidable rectangles. The player's collision box is represented by a rectangle as well. The player can move in 8 directions. The player's velocity is equal in X and Y directions and constant. Each update, I am checking the player's collision against all tiles that are a certain distance away. When the player collides with a rectangle, I am finding the intersection depth and resolving along the most shallow axis followed by the other axis. This resolution happens for both axes simultaneously. See below for two examples of situations where I am having trouble. Moving up-left against the left wall In the scenario below, the player is colliding with two tiles. The tile intersection depth is equal on both axes for the top tile and more shallow in the X axis for the middle tile. Because the player is moving up the wall, the player should slide in an upward direction along the wall. This works properly as long as the rectangle with the more shallow depth is evaluated first. If the equal intersection depth rectangle is evaluated first, there is a chance the player becomes stuck. Moving up-left against the top wall Here is an identical scenario with the exception that the collision is with the top wall. The same problem occurs at the corners when intersection depth is equal for both axes. I guess my overall question is: How can I ensure that collision response occurs on tiles that have non-equal intersection depth before tiles that have equal intersection depth in order to get around the weirdness that occurs at these corners. Sean's answer in the linked question was good, but his solution required having different velocity components in a certain direction. My situation has equal velocities, so there's no good way to tell which direction to resolve at corners. I hope I have made my explanation clear.

    Read the article

1 2 3 4 5 6 7 8 9 10 11 12  | Next Page >