Mouse collision: new Rectangle or move Rectangle?

Started by
2 comments, last by genjihl 11 years, 11 months ago
Hello, please let me know if I'm being way too nit picky or paranoid about my game's performance with my query:

To see if my mouse intersecting a Rectangle (in XNA), I've thought of two ways:

1. Check if the object's Rectangle intersects with a new Rectangle created at the mouse's position.
Or 2. Initialize a rectangle to follow the mouse around, and update its position every time Update() is called, and when the check occurs, simply provide the mouse's Rectangle.

Assuming the check is called very frequently (whenever other classes want to know if the mouse is hitting anything important), which method would be the most efficient? And, is this difference even significant?

If you'd like to see what I mean in code:


//Option #1
class MouseInput
{
[indent=1]MouseState lastState;

[indent=1]MouseState currentState;

[indent=1]public bool Intersects(Rectangle rect)
[indent=1]{
[indent=2]return rect.Intersects ( new Rectangle ( currentState.X, currentState.Y, 1, 1) );
[indent=1]}
[indent=1]public void Update()
[indent=1]{
[indent=2]lastState = currentState;
[indent=2]currentState = Mouse.GetState();
[indent=1]}
}

//Option #2
class MouseInput
{
[indent=1]MouseState lastState;
[indent=1]MouseState currentState;
[indent=1]Rectangle mouseRectangle;

[indent=1]public void Initialize()
[indent=1]{
[indent=2]mouseRectangle = new Rectangle ( currentState.X, currentState.Y, 1, 1);
[indent=1]}

[indent=1]public bool Intersects(Rectangle rect)
[indent=1]{
[indent=2]return rect.Intersects ( mouseRectangle );
[indent=1]}

[indent=1]public void Update()
[indent=1]{
[indent=2]lastState = currentState;
[indent=2]currentState = Mouse.GetState();

mouseRectangle.X = currentState.X;
[indent=2]mouseRectangle.Y = currentState.Y;
[indent=1]}
}
[/quote]

Thanks in advance for the help!
Advertisement

Assuming the check is called very frequently (whenever other classes want to know if the mouse is hitting anything important), which method would be the most efficient? And, is this difference even significant?

In your case it would not really matters if you create or update the rectangle.

But it is best practise to create/delete objects relative seldomly and use an existing object instead, even hold objects in the cache when not needed any longer.
Doesn't Rectangle have a Contains() method? If so, it would be simpler to use that instead of creating a rectangle of size 1 every time.

Doesn't Rectangle have a Contains() method? If so, it would be simpler to use that instead of creating a rectangle of size 1 every time.


You're right, it does. I'll use that instead.

Thanks everyone!

This topic is closed to new replies.

Advertisement