gpt4 book ai didi

java - 如何在处理中将矩形平移到先前的鼠标坐标

转载 作者:行者123 更新时间:2023-12-02 10:53:31 30 4
gpt4 key购买 nike

我是java新手,我正在制作一个贪吃蛇游戏。我的下一步是在蛇吃食物时为其添加一个矩形。我当前的想法是,我想添加一个相同的矩形,该矩形已转换为(mouseX,mouseY)的先前位置。至少,与前一个矩形平移一个矩形的距离,但定位在鼠标先前所在的位置,以“跟随”在其前面的棋子后面。我不知道如何去做,但这是迄今为止我的代码。

//snake
void snake() {
rect(mouseX, mouseY, 10, 10);
}

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, wid, len);
}

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

class Food {

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

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

//update food position
void update() {
if( (mouseX > xcord) && (mouseX < xcord + wid) &&
(mouseY > ycord) && (mouseY < ycord + len)) {
xcord = int(random(width - 5));
ycord = int(random(height - 5));
//lengthen snake
}
}

//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();
}

最佳答案

你创建了 2 个变量

float pMouseX = mouseX;
float pMouseY = mouseY;

然后,在绘图中,更新蛇之后,更新这些变量:

s.update
pMouseX = mouseX;
pMouseX = mouseY;

对于超过 2 个矩形,请考虑使用 ArrayList 而不是单个变量。的arrays .

数组基本上是一种在一个变量中存储多个变量的方法。ArrayList 类似,但它没有固定的大小。这意味着您可以不断向 ArrayList 添加元素,而这是 Array 无法做到的。

你可以像这样声明这样的ArrayList:

ArrayList<float[]> arrayList = new ArrayList<float[]>(); //each element of the ArrayList is an array, which contains an x and y position

要获取任意矩形的 x 和 y 坐标,请使用 arrayList.get(indexOfTheRectangle)[0] //use 1 instead of 0 for the y coordinate 并像这样更新它们:

for (int i = arrayList.length - i; i > 0; i++) { //you need to go through the array backwards, because otherwise, for each element, you end up changing the value it is supposed to get, which results in all elements having the same value.
arrayList[i] = arrayList[i - 1];
}
arrayList[0] = new float[]{mouseX, mouseY}

关于java - 如何在处理中将矩形平移到先前的鼠标坐标,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59867390/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com