Sunday, November 18, 2007

How do I build a rectangle around an object?

Question: How do I build a rectangle around an object?

Answer: By using the Rectangle class, an invisible box can be created and used for collision checking, or for virtually any other purpose.

Rectangle rect = new Rectangle((int)objectPosition.X, (int) objectPosition.Y, objectTexture.Width, objectTexture.Height);

The above code shows a common way a Rectangle is created to wrap an object. The Rectangle constructor takes an X and Y coordinate to be the base corner of the rectangle, and then a width and height for the dimensions of the rectangle. In the code above, we retrieved the X and Y coordinates from a Vector2, and we retrieved the width and height from a Texture2D. This is just one way of creating a Rectangle though, and there are many other possibilities also.

No comments: