One-way platform collision
- by TheBroodian
I hate asking questions that are specific to my own code like this, but I've run into a pesky roadblock and could use some help getting around it. I'm coding floating platforms into my game that will allow a player to jump onto them from underneath, but then will not allow players to fall through them once they are on top, which require some custom collision detection code. The code I have written so far isn't working, the character passes through it on the way up, and on the way down, stops for a moment on the platform, and then falls right through it. Here is the code to handle collisions with floating platforms:
protected void HandleFloatingPlatforms(Vector2 moveAmount)
{
//if character is traveling downward.
if (moveAmount.Y > 0)
{
Rectangle afterMoveRect = collisionRectangle;
afterMoveRect.Offset((int)moveAmount.X, (int)moveAmount.Y);
foreach (World_Objects.GameObject platform in gameplayScreen.Entities)
{
if (platform is World_Objects.Inanimate_Objects.FloatingPlatform)
{
//wideProximityArea is just a rectangle surrounding the collision
//box of an entity to check for nearby entities.
if (wideProximityArea.Intersects(platform.CollisionRectangle) ||
wideProximityArea.Contains(platform.CollisionRectangle))
{
if (afterMoveRect.Intersects(platform.CollisionRectangle))
{
//This, in my mind would denote that after the character is moved, its feet have fallen below the top of the platform, but before he had moved its feet were above it...
if (collisionRectangle.Bottom <= platform.CollisionRectangle.Top)
{
if (afterMoveRect.Bottom > platform.CollisionRectangle.Top)
{
//And then after detecting that he has fallen through the platform, reposition him on top of it...
worldLocation.Y = platform.CollisionRectangle.Y - frameHeight;
hasCollidedVertically = true;
}
}
}
}
}
}
}
}
In case you are curious, the parameter moveAmount is found through this code:
elapsed = (float)gameTime.ElapsedGameTime.TotalSeconds;
float totalX = 0;
float totalY = 0;
foreach (Vector2 vector in velocities)
{
totalX += vector.X;
totalY += vector.Y;
}
velocities.Clear();
velocity.X = totalX;
velocity.Y = totalY;
velocity.Y = Math.Min(velocity.Y, 1000);
Vector2 moveAmount = velocity * elapsed;