Not all elements of an array working
in
Programming Questions
•
5 months ago
I am trying to create a from-scratch version of Space Invaders and as a complete beginner, I'm still working on getting collisions down and I know my work probably looks sloppy compared to most. The issue I am having with the program however, is that only half of the arrays follow the position limits I put in. The ships are obviously supposed to reverse direction and drop upon hitting the edge. Instead, only every other one does this, while the ones that don't fly off into infinity. I have gotten it so that the move as one unit instead of each ship responding individually upon reaching the edge, but it still seems to have the same problem with not acknowledging half of the elements. It also seems to be dependent upon the size of the ships. For instance: if the size of the ships is even, the far right element the odd numbered elements won't work properly, but if the size of the ship is an odd number, the even numbered elements won't work. I added the code below. Thanks in advance.
Ship[]ships = new Ship[10];
int s=2;
int y=50;
boolean posCheck;
void setup(){
size(800,800);
smooth();
int d=100; //size of ship (wanted it to be easily changable)
for(int i = 0; i < ships.length; i++){
ships[i] = new Ship(d);
d=d+75;
}
}
void draw(){
background(255);
for(int i = 0; i<ships.length; i++){
ships[i].fly(s);
ships[i].display(y);
posCheck= ships[i].check();
if(posCheck==true){
s=s*-1;
y=y+50;
}
}
}
class Ship{
int x;
int y1=1;
int speed;
int wid;
boolean ch;
Ship(int x_){
x=x_;
wid=25;
}
void display(int y_){
fill(0);
rectMode(CENTER);
rect(x,y_,wid,wid);
}
void fly(int sp){
x+=sp;
}
boolean check(){
if((x+(wid/2)==width)||(x-(wid/2)==0)){
ch=true;
}
else{ch=false;}
return ch;
}
}
1