better collision-detection with maybe only one bug

GitOrigin-RevId: c205dfcd6c4d36864ca58448244aed9da00d47c8
This commit is contained in:
Colin McMillen 2019-12-15 21:26:39 -05:00
parent 22091fa5b1
commit 11da38ffa6

View File

@ -35,22 +35,33 @@ namespace Jumpy {
AirState oldAirState = airState; AirState oldAirState = airState;
UpdateFromGamePad(time, gamePad); UpdateFromGamePad(time, gamePad);
Rectangle playerBbox = new Rectangle(position.X - spriteWidth, position.Y - 8, spriteWidth * 2, 27); Rectangle oldBbox = new Rectangle(oldPosition.X - spriteWidth, oldPosition.Y - 7, spriteWidth * 2, 26);
Rectangle playerBbox = new Rectangle(position.X - spriteWidth, position.Y - 7, spriteWidth * 2, 26);
bool standingOnGround = false; bool standingOnGround = false;
foreach (var rect in collisionTargets) { foreach (var rect in collisionTargets) {
playerBbox = new Rectangle(position.X - spriteWidth, position.Y - 8, spriteWidth * 2, 27); playerBbox = new Rectangle(position.X - spriteWidth, position.Y - 7, spriteWidth * 2, 26);
// first we check for left-right collisions...
if (playerBbox.Intersects(rect)) {
if (oldBbox.Right <= rect.Left && playerBbox.Right > rect.Left) {
position.X = rect.Left - spriteWidth;
}
if (oldBbox.Left >= rect.Right && playerBbox.Left < rect.Right) {
position.X = rect.Right + spriteWidth;
}
playerBbox = new Rectangle(position.X - spriteWidth, position.Y - 7, spriteWidth * 2, 26);
}
// after fixing that, we check for hitting our head or hitting the ground.
if (playerBbox.Intersects(rect)) { if (playerBbox.Intersects(rect)) {
if (oldPosition.Y > position.Y) { if (oldPosition.Y > position.Y) {
int diff = playerBbox.Top - rect.Bottom; int diff = playerBbox.Top - rect.Bottom;
position.Y -= diff; position.Y -= diff;
ySpeed *= 0.9; // ySpeed *= 0.9;
} else { } else {
airState = AirState.Ground; airState = AirState.Ground;
int diff = playerBbox.Bottom - rect.Top; int diff = playerBbox.Bottom - rect.Top;
position.Y -= diff; position.Y -= diff;
} }
Debug.AddRect(rect, Color.Yellow);
} else { } else {
playerBbox.Height += 1; playerBbox.Height += 1;
if (playerBbox.Intersects(rect)) { if (playerBbox.Intersects(rect)) {