如何return处理矩形边界内的任意点?

How to return any point within the borders of a rectangle in processing?

我是 java 的新手,仅供参考。我正在使用处理,我正在制作贪吃蛇游戏。我的下一步是让食物在蛇吃掉后刷新到一个新位置。问题是 "snake head" 需要与 "food" 矩形完全对齐才能刷新;基本上,鼠标需要在食物的确切中心上方,而不是仅仅触摸它。我该如何调整它,以便一旦鼠标接触到 "food" 矩形它就会刷新?我试过乱用 rectMode(),但是得到了 weird.lol 这就是我到目前为止所拥有的,如果代码是垃圾,请原谅我。就像我说的,java.

是全新的
class Snake {

    //variables
    int len;
    int wid;
    int xcord;
    int ycord;

    //constructor
    Snake(int x,int y, int len, int wid) {
        this.len = len;
        this.wid = wid;
        this.xcord = x;
        this.ycord = y;
        rect(xcord, ycord, len, wid);
    }

    //clear screen
    void  update() {
        background(255);
        rect(mouseX, mouseY, len, wid);
    }    
}

class Food {

    //variables
    int xcord;
    int ycord;

    //constructor
    Food() {
        this.xcord = int(random(width));
        this.ycord = int(random(height));
        rect(xcord, ycord, 10, 10);
    }

    //update food position. This seems like the issue code block
    void update() {
        if( mouseX == xcord && mouseY == ycord) {
            xcord = int(random(width));
            ycord = int(random(height));
        }
    }

    //display food
    void displayFood() {
        rect(xcord, ycord, 10, 10);
    }
}

Snake s;
Food f;
void setup() {
background(255);
    s = new Snake(mouseX, mouseY, 10, 10);
    f = new Food();
}

void draw() {
    s.update();
    f.update();
    f.displayFood();
}

您有 class 游戏处理程序来控制 Snake 和食物?您可以查看 isFoodIntersectSnake()。并在食物不与蛇体相交的情况下生成新的食物位置。

对于正确的刷新食物,您必须检查蛇头是否与食物位于同一矩形:

boolean isSnakeEatFood(Snake snake, Food food){
    return snake.xcord == food.xcord &&  snake.ycord == food.ycord
}

要检查矩形的碰撞,您必须检查矩形在两个维度上是否重叠。

对于每个维度,都有以下可能的情况(维度 x 的示例):

不重叠:

x1      x1+w1
  +----+
            +----+
          x2      x2+w2
           x1      x1+w1
             +----+
  +----+
x2      x2+w2

重叠

x1                x1+w1
  +--------------+
       +----+
     x2      x2+w2
     x1      x1+w1
       +----+
  +---------------+
x2                 x2+w2
x1           x1+w1
  +---------+
       +----------+
     x2            x2+w2
     x1            x1+w1
       +----------+
  +----------+
x2            x2+w2

这意味着,范围重叠如果

x1 < x2+w2 AND x2 < x1+w1

这导致方法中出现以下情况update

class Food {
    // [...]

    void update() {

        if( mouseX < xcord+10 && xcord < mouseX+10 &&
            mouseY < ycord+10 && ycord < mouseY+10) {

            xcord = int(random(width));
            ycord = int(random(height));
        }
    }

    // [...]
}