I'm making a game where basically you dodge incoming asteroids as a spaceship (it's for a first year university project).
I've got a problem though, I call in 6 object from a class (asteroids), they are called in via an array. I need to be able to use their x and y positions outside of the class in order to detect if the user controlled sprite has collided with one.
Whenever I try to refer to the x or y position of the asteroids outside of the class I get the error "Cannot make a static reference to the non-static field obstacle.posx".
Below is an MCVE of my code. It calls in the objects and they move down the screen. I have removed the user controlled sprite and images for now as all I need to know is how to refer to the objects positions outside of the class.
*I've added some changes that display what I'm trying to achieve
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)));
}
}
}
collision()method is still problematic. Try something like this: void collision () { for (int i = 0; i < asterioid.length; ++i) { if (x == asteroid[i].posx && y == asteroid[i].posy) { println("Hit"); break; } } }