我正在制作类似于agar.io的游戏,其中一个小球四处走动并吃点东西。我在手机上制作,您用手指控制斑点以收集点。我注意到当我收集一个点时,一些随机的其他点也消失了。我进行了一些调试,发现除非您按照将点添加到阵列中的顺序收集点,否则任何具有较低阵列顺序的点都将被销毁。例如:如果您收集了添加到第7个数组中的点,则点0-6将消失;如果您收集了1然后是2,则位将消失,依此类推,那么其他点将不会随机消失。我创建了另一个更简单的示例来探讨这个问题。现在,它是一个具有5个圆圈的简单屏幕。您可以拾取和拖放任何圆圈。我注意到了同样的问题,即使没有代码使它们消失,但您拖动一个圆并随机消失其他圆。我的代码如下:
// Drag n' Drop //
Objects[] box;
int objCount = 5;
void setup() {
box = new Objects[objCount];
for (int i = 0; i < objCount; i++){
box[i] = new Objects(random(displayWidth),random(displayHeight),200);
}
}
void draw() {
background(170);
for (Objects boxes : box) {
boxes.display();
boxes.dragging();
}
}
class Objects {
float x, y;
float s;
Objects(float tempX, float tempY, int tempS) {
x = tempX;
y = tempY;
s = tempS;
}
void display() {
ellipse(x, y, s, s);
}
void dragging() {
if (dist(x, y, mouseX, mouseY) < 500) {
x = mouseX;
y = mouseY;
s = 300;
}
}
}
我相信我的问题可能出在我用来调用box对象的display函数的循环中,但是我找不到其他方法可以使它工作。任何帮助我们都非常感谢。感谢您的时间。 PS Im使用处理来运行此代码。
答案 0 :(得分:2)
首先,我要感谢您,因为我以前从未玩过Processing,您启发了我下载它!
我想指出很多错误,也许会引导您走向正确的方向。主要问题在于您的dragging()
方法中,您实际上并没有删除对象,只是将它们移动到鼠标位置,给您一种被删除的错觉!
无论如何,正如您所说的,您正在创建游戏Agar.io,我认为您自己应该拥有自己的Blob
。为了我的Java头脑,我将您所说的Objects
切换为Blobs
。
首先,设置。
import java.util.*;
public static final int BLOB_COUNT = 10;
List<Blob> blobs = new ArrayList<Blob>();
// this is our blob, the one that displays in the middle of the screen
Blob myBlob = new Blob(mouseX, mouseY, 50);
void setup() {
size(1000, 500);
for (int i = 0; i < BLOB_COUNT; i++){
blobs.add(new Blob(random(displayWidth/2),random(displayHeight/2),50));
}
}
请注意我如何使用ArrayLists
而不是数组,这将使您更轻松地从列表中添加和删除列表。
接下来是draw(),所以每帧都会发生一次。
void draw() {
background(170);
// refreshes the players blob wherever the cursor is!
myBlob.setX(mouseX);
myBlob.setY(mouseY);
myBlob.display();
// display the other blobs on the screen
for (Blob boxes : blobs) {
boxes.display();
boxes.dragging();
}
}
注意,我们想将Blob更新为鼠标的当前位置!
最后,Blob类!
class Blob {
float x, y;
float size;
Blob(float tempX, float tempY, int size) {
this.x = tempX;
this.y = tempY;
this.size = size;
}
void display() {
ellipse(x, y, size, size);
}
void dragging() {
if (dist(x, y, mouseX, mouseY) < myBlob.getSize()/2) {
myBlob.setBlobSize(25);
this.x = random(displayWidth/2);
this.y = random(displayHeight/2);
}
}
void setX(float x){
this.x = x;
}
void setY(float y) {
this.y = y;
}
void setBlobSize(float size) {
this.size += size;
}
float getSize() {
return this.size;
}
}
因此,现在,我们检查dragging()方法中的斑点是否接近我们的斑点,如果是我们要消耗该斑点(这会增加质量),然后希望该斑点重新生成为另一个位置,这就是大多数Agar.io游戏的工作方式,但这当然完全取决于您。还有很多更精确的方法可以计算blob的面积并确定两个blob是否在接触距离之内,但是我将把数学问题留给您。