简体   繁体   English

从哪一侧进行C#XNA矩形碰撞检测

[英]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. 尝试使用此模板,然后将您的游戏逻辑纳入其中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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