I'm making a simple game in C# and i'm having some problems with rectangle collisions. What i'm doing is checking if two rectangles intersects, checking the side of collision and then moving the rectangles away from each other.
What is working:
- The rectangle intersection check is working.
- The left and right rectangle side collisions is working.
What is not working:
- When debugging, the collision check only prints "Touching Left/Right".
- When i move a rectangle to the top or bottom side of another, the first rectangle jumps to the other side.
- The second problem works correctly if the first rectangle is alligned perfectly to the top or bottom side.
Here is a snippet of the code that i currently have, i hope someone can help me solve these problems.
public RectangleF Bounds { get { return new RectangleF(position.x, position.y, scale.width, scale.height); } }
public void CheckCollisions(Transform first, Transform second)
{
if(first.Bounds.IntersectsWith(second.Bounds) == false) return;
bool touching_left =
first.Bounds.Right > second.Bounds.Left &&
first.Bounds.Left < second.Bounds.Left &&
first.Bounds.Bottom > second.Bounds.Top &&
first.Bounds.Top < second.Bounds.Bottom;
bool touching_right =
first.Bounds.Left < second.Bounds.Right &&
first.Bounds.Right > second.Bounds.Right &&
first.Bounds.Bottom > second.Bounds.Top &&
first.Bounds.Top < second.Bounds.Bottom;
bool touching_top =
first.Bounds.Bottom > second.Bounds.Top &&
first.Bounds.Top < second.Bounds.Top &&
first.Bounds.Right > second.Bounds.Left &&
first.Bounds.Left < second.Bounds.Right;
bool touching_bottom =
first.Bounds.Top < second.Bounds.Bottom &&
first.Bounds.Bottom > second.Bounds.Bottom &&
first.Bounds.Right > second.Bounds.Left &&
first.Bounds.Left < second.Bounds.Right;
if (touching_left)
{
float x = second.Bounds.Left - first.Bounds.Width;
float y = first.Bounds.Y;
first.SetPosition(new PointF(x, y));
Debug.WriteLine("Touching LEFT");
}
else if (touching_right)
{
float x = second.Bounds.Right;
float y = first.Bounds.Y;
first.SetPosition(new PointF(x, y));
Debug.WriteLine("Touching RIGHT");
}
else if (touching_top)
{
float x = first.Bounds.X;
float y = second.Bounds.Top - first.Bounds.Height;
first.SetPosition(new PointF(x, y));
Debug.WriteLine("Touching TOP");
}
else if (touching_bottom)
{
float x = first.Bounds.X;
float y = second.Bounds.Bottom;
first.SetPosition(new PointF(x, y));
Debug.WriteLine("Touching BOTTOM");
}
}
Thanks in advance!