简体   繁体   中英

C# XNA rectangle collision detecting from which side

I have a player rectangle and a wall rectangle. I'm trying to determine from which side the player hit the wall.

For example, if the player hit the wall from his left side, then the player can't keep going left through the wall but can go up, down or right.

How can I determine from which side the player hit the wall?

Before you update the player's position and rectangle, keep a record of the old rectangle so it can be compared to the new position. For example:

// Keep a record of old rectangle
Rectangle oldPos = player.Rectangle;

// Update player position and rectangle here

// Check for collision
if (player.Rectangle.Intersects(wallRect))
{
    // Player has hit the wall. Now to find out which direction it has come from

    if (oldRect.Center.X < wallRect.Center.X)
    {
        // Player came from left of wall
    }
    else
    {
        // Player came from right of wall
    }
}

Try this for a template and work your game logic into it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM