我对编程非常陌生,我选择了C#作为入门语言。现在我正在尝试制作我的第一个游戏,我决定做贪吃蛇。到目前为止,我一直在研究这个问题,但是所有我看到的答案都是针对使用不同方法移动蛇的人的。
我的程序使用两个double值(left和top)来存储蛇在画布上的位置。我的程序还使用两个double值来表示游戏中的“食物”,称为randomFoodSpawnLeft和randomFoodSpawnTop。
我的问题是:如何仅使用left和top值检测两个矩形对象之间的碰撞?我很困惑。
snakeWindow是窗口,snakeHead是代表蛇的矩形,left是蛇的左侧值,top是蛇的顶部值。
我的程序使用两个double值(left和top)来存储蛇在画布上的位置。我的程序还使用两个double值来表示游戏中的“食物”,称为randomFoodSpawnLeft和randomFoodSpawnTop。
我的问题是:如何仅使用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);
}
if
语句替代四个来执行碰撞测试(参见 intersect)。问题不清楚:每个矩形都有坐标(左,上)和尺寸(宽度,高度)。问题在哪里? - SinatrIntersectsWith
是System.Drawing.Rectangle
上的一个方法;也许你正在使用System.Windows.Shapes.Rectangle
? - Scroog1