Rectangle Intersects Method

Hello, I’m not sure if this is the right place to ask but I have a lasting problem with rectangle.Intersects() method in monogame.

I’m using a combination of Tiled and Monogame together, and have used the following logic to implement a collision system.

foreach (var o in map.ObjectGroups[“collision”].Objects)
{
collisionObjects.Add(new Rectangle((int)o.X + bounds.X, (int)o.Y + bounds.Y, (int)o.Width, (int)o.Height));
}

=for loading the objects that will collide and,

foreach (var rect in _collisionObjects)
{
if (rect.Intersects(Rectangle))
{
Position = initPos;
Velocity = Vector2.Zero;
}
else
{
Position += Velocity;
Velocity = Vector2.Zero;
}
}

=for stopping the player when an obstacle is detected.

It does work fine in some aspects but the problem is that the size of the rectangle to which it collides is always off by 1, or half a pixel which results in the size of the obstacle not equating to the dimensions it was originally created as.

I have attempted to debug this problem by adding the following code

foreach (var VARIABLE in _collisionObjects)
{
spriteBatch.DrawRectangle(VARIABLE, Color.Azure);
}

This line(s) of code draws the rectangle of the obstacle that is in _collisionObjects.

image
image
image
image

I wouldn’t have had a hard time if the offsets were constant across all obstacles, but problem is that they all vary and seems to carry no pattern.

I know monogame isn’t joking with me and there’s a 100% certainty that I’m the one at fault here but I couldn’t get a grasp of why and how the obstacle dimension could go off and I thought I really would want some help or insights from you guys.

Please help me…

Its hard to tell but from the code but this could be due to Velocity being >= 2.0f?

You are adding the velocity and testing collisions the next time round.
If it collides, it looks like you reset to the previous position by setting to initPos.
This will presumably move it back “Velocity” in the direction it came.
So if Velocity > 1 in either direction, it will move back > 1 pixels.

Take a look at Monogame.Extended.Tweening which deals with this problem.

1 Like

Jesus Christ, thank you so much for helping out. Velocity indeed was the problem. Now I’m wondering how I could speed up while not messing up everything else but I guess that would be my job to do.

Thank you very much again :))

1 Like