I have a list of game objects I'm trying to check collision against. I've used the Debug class to write to the console and it seems that i'm getting a collision where there is none.
private bool Intersects(Rectangle player, Rectangle other, CollisionDirection direction, out Vector2 depth)
{
if (direction == CollisionDirection.Vertical)
{
depth = new Vector2(0, GetVerticalIntersectionDepth(player, other));
}
else
depth = new Vector2(GetHorizontalIntersectionDepth(player, other));
return depth.Y != 0 || depth.X != 0;
}
public float GetHorizontalIntersectionDepth(Rectangle rectA, Rectangle rectB)
{
float halfWidthA = rectA.Width / 2;
float halfWidthB = rectB.Width / 2;
float centerA = rectA.Left + halfWidthA;
float centerB = rectB.Left + halfWidthB;
float distanceX = centerA - centerB;
float minDistanceX = halfWidthA + halfWidthB;
if (Math.Abs(distanceX) >= minDistanceX)
return 0;
return distanceX > 0 ? minDistanceX - distanceX : -minDistanceX - distanceX;
}
public float GetVerticalIntersectionDepth(Rectangle rectA, Rectangle rectB)
{
float halfWidthA = rectA.Height / 2;
float halfWidthB = rectB.Height / 2;
float centerA = rectA.Top + halfWidthA;
float centerB = rectB.Top + halfWidthB;
float distanceX = centerA - centerB;
float minDistanceX = halfWidthA + halfWidthB;
if (Math.Abs(distanceX) >= minDistanceX)
return 0;
return distanceX > 0 ? minDistanceX - distanceX : -minDistanceX - distanceX;
}
private void CheckCollisions(CollisionDirection direction, List<GameObject> objects)
{
foreach(GameObject obj in objects)
{
Vector2 depth;
if(Intersects(CollisionRectangle, obj.g_CollisionRectangle, direction, out depth))
{
g_WorldPosition += depth;
Debug.WriteLine("true");
if (direction == CollisionDirection.Horizontal)
g_Velocity.Y = 0;
else
g_Velocity.X = 0;
}
}
}
And in my update method.
....
if(ks.IsKeyDown(Keys.S))
{
g_WorldPosition.Y += 10f;
playerFacing = Direction.DOWN;
CheckCollisions(CollisionDirection.Vertical, objectList);
}
if(ks.IsKeyDown(Keys.A))
{
g_WorldPosition.X -= 10f;
playerFacing = Direction.LEFT;
CheckCollisions(CollisionDirection.Horizontal, objectList);
}
...
In the CheckCollision method the Debug line is writing true to the output even when i'm not colliding with anything. I know the g_CollisionRectangle is being set correctly because I have lines being drawn around the outside of each collidable object.
What happens is my player kinda moves sporadically because I'm getting collisions in places where I shouldnt. Can anyone see where I'm going wrong here? I realize that g_Velocity is not being used in my update method, but I don't think that it should effect what is happening at this point. From what I can tell, my GetVertical and GetHorizontal methods are wrong somewhere because of the Debug line in the CheckCollision method.