贪吃蛇游戏 - 让碰撞处理图像
本文关键字:碰撞 处理 图像 游戏 | 更新日期: 2023-09-27 18:37:28
当我使用矩形作为食物时,这很有效,但现在我正在尝试使用自己的图像来制作食物,但无法使其正常工作。使用IntersectsWith
时,我不断收到"无法将图像转换为矩形"的错误,所以我被困在那里,不知道该怎么办。
我的错误在于代码的这一部分:if (snake.SnakeRec[i].IntersectsWith(food.foodRec))
for (int i = 0; i < snake.SnakeRec.Length; i++)
{
if (snake.SnakeRec[i].IntersectsWith(food.foodRec))
{
score += 10;
snake.growSnake();
food.foodLocation(randFood);
}
}
collision();
this.Invalidate();
在食品.cs类
public void drawFood(Graphics paper)
{
Image foodRec = Image.FromFile(@"C:'food.bmp");
Rectangle rectangleAreaToDrawImage = new Rectangle(x, y, width, height);
paper.DrawImage(foodRec, rectangleAreaToDrawImage);
}
如果您需要更多代码,请告诉我。
编辑:已解决
我不得不改变:
if (snake.SnakeRec[i].IntersectsWith(food.foodRec))
Rectangle rectangleAreaToDrawImage = new Rectangle(x, y, width, height);
自:
if (snake.SnakeRec[i].IntersectsWith(food.rectangleAreaToDrawImage))
rectangleAreaToDrawImage = new Rectangle(x, y, width, height);
不是将图像发送到IntersectsWith
而是需要发送图像矩形,如下所示:
// Instead of this:
if (snake.SnakeRec[i].IntersectsWith(food.foodRec))
// Put this:
if (snake.SnakeRec[i].IntersectsWith(food.rectangleAreaToDrawImage))
我假设rectangleAreaToDrawImage
是公开可用的,因为您使用的是同一类中的foodRec
。
希望这有帮助!
你现在的代码将foodRec定义为图像而不是矩形。尝试将 foodRec 定义为具有图像尺寸的矩形。