C#矩形碰撞检测不能正常工作

时间:2016-08-14 17:16:52

标签: c# xna collision

Hy大家,所以我在C#/ XNA做一个小游戏 我碰到这个问题。

基本上我在我的代码中做的是我做一个普通的玩家运动,而不仅仅是检查是否按下了向上键,它还检查玩家CanGoTop == true;

        public void RectangleInteraction(Rectangle anotherRectangle)
    {
        if (playerRectangle.Bottom <= anotherRectangle.Top &&
            playerRectangle.Top >= (anotherRectangle.Top - playerRectangle.Height) &&
            playerRectangle.Left <= anotherRectangle.Right &&
            playerRectangle.Right >= anotherRectangle.Left)
        {
            CanGoBot = false;
        }
        else CanGoBot = true;


        if (playerRectangle.Top >= anotherRectangle.Bottom &&
            playerRectangle.Bottom <= (anotherRectangle.Bottom + playerRectangle.Height) &&
            playerRectangle.Left <= anotherRectangle.Right &&
            playerRectangle.Right >= anotherRectangle.Left)
        {
            CanGoTop = false;
        }
        else CanGoTop = true;


        if (playerRectangle.Top <= anotherRectangle.Bottom &&
            playerRectangle.Bottom >= anotherRectangle.Top &&
            playerRectangle.Right <= anotherRectangle.Left &&
            playerRectangle.Left >= (anotherRectangle.Left - playerRectangle.Width))
        {
            CanGoRight = false;
        }
        else CanGoRight = true;


        if (playerRectangle.Top <= anotherRectangle.Bottom &&
            playerRectangle.Bottom >= anotherRectangle.Top &&
            playerRectangle.Left >= anotherRectangle.Right &&
            playerRectangle.Right <= (anotherRectangle.Right + playerRectangle.Width))
        {
            CanGoLeft = false;
        }
        else CanGoLeft = true;

    }

我这样做是为了左,右,上,下,如果一个bollean是假的,玩家将不会移动(在移动的4个定义之后有一个其他的定义,将速度设置为x和.y为0)< / p>

好的,现在我在我的Player类中创建了一个方法,你就会明白这个想法 通过简单地看一下它是什么,我不认为我必须解释这里发生了什么:

post_parent

然后在我的Game1.cs Update()方法中,我使用我的播放器实例在那里调用那个方法,现在有些东西让我很烦恼,适用于CanGoLeft,但对于其他3个bool,它没有&# 39;吨

我真的不知道为什么,这是我用InGameMsgs的4个屏幕截图来帮助我,并且用我的代码检查这些消息告诉我CollisionLogic很好,但其他错误。 为什么只有CanGoLeft工作呢? :/

感谢您的时间和帮助。

CanGoLeft CanGoBot

1 个答案:

答案 0 :(得分:1)

你的逻辑似乎在几个方面被打破了。您应该使用RectangleOffset这样的Rectangle方法来检查目标distance是否会合并。我认为这接近你的意图(假设public void RectangleInteraction(Rectangle anotherRectangle) { Rectangle down = playerRectangle; down.Offset(0, distance); Rectangle up = playerRectangle; up.Offset(0, -distance); Rectangle left = playerRectangle; left.Offset(-distance, 0); Rectangle right = playerRectangle; right.Offset(distance, 0); ConGoBot = !down.Intersects(anotherRectanlge); ConGoTop = !up.Intersects(anotherRectanlge); ConGoLeft = !left.Intersects(anotherRectanlge); ConGoRight = !right.Intersects(anotherRectanlge); } 是玩家移动的价值):

Rectangle

(假设您使用的是Intersects,.net框架中还有其他<link rel="stylesheet" type="text/css" href="style.css" />结构,但您的问题已标记为Microsoft.Xna.Framework.Rectangle