我正在制作一款游戏,基本上你可以像一艘宇宙飞船一样躲避来袭的小行星(这是大学一年级的项目)。
但是我遇到了一个问题,我从一个类(小行星)中调用了 6 个对象,它们是通过数组调用的。我需要能够在类之外使用它们的 x 和 y 位置,以便检测用户控制的 Sprite 是否与 Sprite 发生碰撞。
每当我尝试引用类之外的小行星的 x 或 y 位置时,我都会收到错误“无法对非静态场障碍物进行静态引用。posx”。
下面是我的代码的 MCVE。它调用对象,然后它们在屏幕上向下移动。我现在已经删除了用户控制的 Sprite 和图像,因为我需要知道的是如何引用类之外的对象位置。
*我添加了一些更改来显示我想要实现的目标
obstacle [] asteroid;
int x;
int y = 400;
int velocity = 10;
void setup ()
{
size (700, 500);
asteroid = new obstacle[6];
for (int i = 0; i < asteroid.length; i++) {
asteroid[i] = new obstacle();
}
}
void draw () {
background(0);
collision();
rect (x,y,30,30);
for (int i = 0; i < asteroid.length; i++) {
asteroid[i].display();
asteroid[i].move();
}
}
void keyPressed () {
if (key == CODED) {
if (keyCode == RIGHT) {
x += velocity;
}
if (keyCode == LEFT) {
x -= velocity;
}
}
}
void collision () {
if (x == obstacle.posx && y == obstacle.posy) {
println("Hit");
}
}
class obstacle {
int velocity = 6;
int posx;
int posy = height;
void display () {
rect (posx, posy, 50, 50);
}
void move() {
posy += velocity;
if (posy >= height) {
posy = (int(random(-500, -50)));
posx = (int(random(20, 650)));
}
}
}
最佳答案
回复:你最后的评论,那是你的问题。您无法引用 obstacle.posx
,因为 obstacle
是类类型,而 posx
不是静态的。您可以将其移至 for 循环内并执行 System.out.println(asteroids[i].posx)
(假设 posx
在那里可见(即它是公共(public)的)。
关于java - 使用类的对象数组进行碰撞,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29219978/