public static bool AABBIsOverlapping(Vector2 mCornerMin1, Vector2 mCornerMax1, Vector2 mCornerMin2,
Vector2 mCornerMax2)
{
if (mCornerMax1.X <= mCornerMin2.X || mCornerMin1.X >= mCornerMax2.X)
return false;
if (mCornerMax1.Y <= mCornerMin2.Y || mCornerMin1.Y >= mCornerMax2.Y)
return false;
return true;
}
public void Update()
{
Velocity += World.Gravity;
Vector2 next = Velocity;
bool xCollided = false;
bool yCollided = false;
List<SSSPBody> toCheck = World.SpatialHash.GetNearbyItems(this);
for (int i = 0; i < toCheck.Count; i++)
{
SSSPBody body = toCheck[i];
if (body != this)
{
Vector2 nextCornerMin = CornerMin + new Vector2(next.X, 0);
Vector2 nextCornerMax = CornerMax + new Vector2(next.X, 0);
if (SSSPUtils.AABBIsOverlapping(nextCornerMin, nextCornerMax, body.CornerMin, body.CornerMax))
{
xCollided = true;
float left = (body.CornerMin.X - nextCornerMax.X);
float right = (body.CornerMax.X - nextCornerMin.X);
if (Math.Abs(left) < right)
Position = new Vector2(Position.X + next.X + left, Position.Y);
else
Position = new Vector2(Position.X + next.X + right, Position.Y);
next = new Vector2(0, next.Y);
Velocity = new Vector2(0, next.Y);
}
nextCornerMin = CornerMin + new Vector2(0, next.Y);
nextCornerMax = CornerMax + new Vector2(0, next.Y);
if (SSSPUtils.AABBIsOverlapping(nextCornerMin, nextCornerMax, body.CornerMin, body.CornerMax))
{
yCollided = true;
float top = (body.CornerMin.Y - nextCornerMax.Y);
float bottom = (body.CornerMax.Y - nextCornerMin.Y);
if (Math.Abs(top) < bottom)
{
Position = new Vector2(Position.X, Position.Y + next.Y + top);
Velocity = new Vector2(next.X, 0);
}
else
{
Position = new Vector2(Position.X, Position.Y + next.Y + bottom);
Velocity = new Vector2(next.X, 0.01f);
}
next = new Vector2(next.X, 0);
}
}
}
if (xCollided == false)
Position = new Vector2(Position.X + next.X, Position.Y);
if (yCollided == false)
Position = new Vector2(Position.X, Position.Y + next.Y);
}