# How to handle collision detection

So the way that I am doing the movement for my game is that you can left click a unit (which is just a rectangle object), and then it is selected. While it is selected, you can right click and that will be the unit's destination.

This is the process input method:

    public void ProcessInput(Vector2 mouseLoc)
{
// SO, I have to take this mouse location, which is the location on the screen
// And convert it to a "world" coordinate

Vector2 distance = new Vector2(mouseLoc.X - position.X, mouseLoc.Y - position.Y);

if (distance.Length() < speed)
{
position = mouseLoc;
isMoving = false;
}
else
{
distance.Normalize();
Vector2 toMove = new Vector2((int)(distance.X * speed), (int)(distance.Y * speed));
position += toMove;
bounds = new BoundingSphere(new Vector3(position, 0), radius);
}
}


I have a basic Wall class that is essentially just another rectangle object but with different properties like textures and what not.

This is my check collision method with the wall:

    public Boolean checkCollision(Wall wall)
{
if (wall.Bounds.Intersects(this.bounds))
{
Vector2 direction = new Vector2((position.X - destination.X) * -1,
(position.Y - destination.Y) * -1);
direction.Normalize();
position += direction * 5;
destination = position;
return true;
}
return false;
}


The problem is that the unit just kinda gets stuck in the wall when it hits it. I'm wondering what is the best way to fix this problem. I know that I have to move the unit out of that spot, but I'm not sure how to.

Any thoughts on how to handle this are appreciated.

• Is this an issue with collision detection or pathfinding? What is the intended behavior when your unit collides with the wall? It seems to me as if your collision is already handled by wall.Bounds.Intersects(this.bounds) Commented Sep 30, 2016 at 6:22
• Sounds more like collision resolution you are interested in. You have found the collision (detected) you are just not quite handling it right. You could try move first and store the new location in a temporary variable, and then check if the temp collides and if so then don't move the original. Commented Nov 16, 2016 at 10:47
• Judging from the code, it is in a 2D plane? If the objects are rectangles, there is no need for a boundingsphere. Rectangle has an intersect method- as a bonus it returns the overlapping rectangle. This provides the infomation you need to know how deep the object penetrates the wall object. Commented Nov 17, 2018 at 8:10