We are about to switch to a new forum software. Until then we have removed the registration on this forum.
MAIN CLASS:
int naveX, naveY;
int inimigoX, inimigoY;
Tiro [] tiros;
boolean tiroVisivel;
boolean naveDireita, naveEsquerda;
void setup(){
size (800, 600);
naveX = 375; naveY = height - 120;
inimigoX = 385; inimigoY = 0;
tiroVisivel = false;
naveDireita = naveEsquerda = false;
}
void draw(){
background (0);
nave();
movimentoNave();
if (tiroVisivel == true && tiros != null){
for (int i = 0; i < tiros.length; i++){
tiros[i].display();
tiros[i].update();
}
}
inimigo();
}
void nave(){
stroke (255);
fill (255, 0, 0);
rect (naveX, naveY, 50, 100);
}
void movimentoNave(){
if (naveEsquerda == true && naveX > 0){
naveX = naveX - 5;
}
if (naveDireita == true && naveX < width - 50){
naveX = naveX + 5;
}
}
void inimigo(){
stroke (255);
fill (0, 100, 255);
rect (inimigoX, inimigoY, 30, 50);
}
void keyPressed(){
if (key == ' '){
append(tiros, new Tiro(naveX + 20, naveY - 30));
tiroVisivel = true;
}
if(key == 'a' || key == 'A'){
naveEsquerda = true;
}
if(key == 'd' || key == 'D'){
naveDireita = true;
}
if (key == 'r' || key == 'R'){
setup();
}
}
void keyReleased(){
if(key == 'a' || key == 'A'){
naveEsquerda = false;
}
if(key == 'd' || key == 'D'){
naveDireita = false;
}
}
PROJECTILE CLASS:
public class Tiro {
private int tiroX = naveX + 20;
private int tiroY = naveY - 30;
public Tiro(int x, int y){
this.tiroX = x;
this.tiroY = y;
}
void display(){
stroke (255);
fill (255, 0, 100);
rect (tiroX, tiroY, 10, 20);
}
void update(){
if (tiroY > 0){
tiroY = tiroY - 10;
}
}
}
Im using append on an empty array to create multiple projectiles, but every time I hit the spacebar Im getting a NullPointerException and I can't figure out why.
Answers
Please edit your post, select your code and hit ctrl+o to format your code. Make sure there is an empty line above and below your code
Kf
Function append() creates a new clone of the passed array, plus the new element:
https://Processing.org/reference/append_.html
Given it doesn't directly mutate the original array, we need to re-assign its returned array back to the variable holding the former:
tiros = (Tiro[]) append(tiros, new Tiro(naveX + 20, naveY - 30));
P.S.: An ArrayList container is a much better fit for when the array's length constantly changes: *-:)
https://Processing.org/reference/ArrayList.html
Check the following code with discussed implementations. Notice that I changed your Tiro class and because of that change, you won't need the following variable declaration: tiroVisivel as far as I can see in your code.
Check for info: https://processing.org/reference/ArrayList.html
Kf