c# - 检测 WPF Canvas 上两个矩形之间的碰撞

标签 c# wpf collision-detection

我是编程新手,我刚开始使用 C#。我现在正在尝试制作我的第一款游戏,我决定使用蛇。到目前为止,我一直在努力研究这个问题,但我看到的所有答案都与使用不同方法移动蛇的人有关。

我的程序使用两个 double (lefttop)来存储蛇在 Canvas 上的位置。我的程序还为游戏中的“食物”使用了两个 double ,分别称为 randomFoodSpawnLeftrandomFoodSpawnTop

我的问题是这样的。如何检测两个仅具有 left 和 top 值的矩形对象之间的碰撞?我很困惑。

snakeWindow是窗口,snakeHead是代表蛇的矩形,left是蛇的左值, top 是蛇的最高值。

void timer_Tick(object sender, EventArgs e)
    {
        double left = Canvas.GetLeft(snakeHead);
        double top = Canvas.GetTop(snakeHead);

        if (keyUp)
        {
            top -= 3;
        }
        else if (keyDown)
        {
            top += 3;
        }
        else if (keyLeft)
        {
            left -= 3;
        }

        else if (keyRight)
        {
            left += 3;
        }
        // These statements see if you have hit the border of the window, default is 1024x765
        if (left < 0)
        {
            left = 0;
            gameOver = true;
        }
        if (top < 0)
        {
            top = 0;
            gameOver = true;
        }
        if (left > snakeWindow.Width)
        {
            left = 0;
            gameOver = true;
        }
        if (top > snakeWindow.Height)
        {
            top = 0;
            gameOver = true;
        }
        // Statements that detect hit collision between the snakeHead and food
        //
        if (foodEaten == true)
        {
            spawnFood();
            textBlockCurrentScore.Text += 1;
        }

            // If gameOver were to be true, then the game would have to end. In order to accomplish this I display to the user that the game is over
            // and the snakeHead is disabled, and should restart.
            if (gameOver == true)
        {
            keyRight = false;
            keyLeft = false;
            keyUp = false;
            keyDown = false;
            top = 0;
            left = 0;

            textBlockGameOver.Text = "GAME OVER!";
            snakeCanvas.Background = Brushes.Blue;
        }


        Canvas.SetLeft(snakeHead, left);
        Canvas.SetTop(snakeHead, top);
    }

最佳答案

您可以使用 System.Windows.Rect.IntersectsWith .像这样尝试:

Rect rect1 = new Rect(left1, top1, widht1, height1);
Rect rect2 = new Rect(left2, top2, widht2, height2);

bool intersects = rect1.IntersectsWith(rect2);

当然,你必须检查蛇的头和它的所有部分。

关于c# - 检测 WPF Canvas 上两个矩形之间的碰撞,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34738882/

相关文章:

c# - Visual Studio Intellisense颜色编码不起作用

c# - Wpf MVVM 如何处理 ViewModel 中的 TextBox "paste event"

java - 创建一个垂直横向卷轴,在数组列表和逻辑方面遇到问题(Java)

安卓碰撞检测精度

c# - 如何根据域名加载不同的Layout页面?

C# 和 Mono 从 Raspberry Pi 访问 Azure?

c# - 在类库项目中实现 IValueConverter

c# - 在具有多种对象类型的 TreeView 中处理 SelectedItemChanged

c# - 从桌面应用程序使用时的PasswordVault安全性

java - 基于图 block 的碰撞;角部碰撞问题