1

This works when I used a rectangle as the food but now I'm trying to use my own image for the food but can't get it to work correctly. I keep getting the error of "Cannot convert Image to Rectangle" when using IntersectsWith so I'm stuck there and not sure what to do.

My error is on this part of the code: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();

In the Food.cs class

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 you need more code let me know.

Edit: Solved

I had to change:

if (snake.SnakeRec[i].IntersectsWith(food.foodRec))

Rectangle rectangleAreaToDrawImage = new Rectangle(x, y, width, height);

to:

if (snake.SnakeRec[i].IntersectsWith(food.rectangleAreaToDrawImage))

rectangleAreaToDrawImage = new Rectangle(x, y, width, height);

4

2 回答 2

1

而不是将图像发送到IntersectsWith您需要发送图像矩形,如下所示:

// Instead of this:
if (snake.SnakeRec[i].IntersectsWith(food.foodRec))
// Put this:
if (snake.SnakeRec[i].IntersectsWith(food.rectangleAreaToDrawImage))

我假设rectangleAreaToDrawImage是公开可用的,因为您使用foodRec的是同一个班级。

希望这可以帮助!

于 2012-06-16T05:04:07.360 回答
0

您现在的代码将 foodRec 定义为图像而不是矩形。尝试将 foodRec 定义为具有图像尺寸的矩形。

于 2012-06-16T05:04:32.157 回答