Trying to write a simple snake game with arrays but I run into an error

float[] xpos;
float[] ypos;
void setup() {
  size(500,500);
}
void draw() { 
  background(255);
  for (int i = 0; i < xpos.length - 1; i++) {
    xpos[i] = xpos[i + 1]; 
    ypos[i] = ypos[i + 1]; 
  } 
  xpos[xpos.length-1] = mouseX; 
  ypos[ypos.length-1] = mouseY; 
  for (int i = 0; i < xpos.length; i++) { 
    noStroke();  
    fill(255-i*5); 
    ellipse(xpos[i],ypos[i],i,i); 
  }
} 

It gives me NullPointerException on line 8

1 Like

Hello,

Declare and create a new array:

float[] xpos = new float[50];
float[] ypos = new float[50];

Now xpos.length will equal something!

References:
https://processing.org/tutorials/arrays/
https://processing.org/reference/Array.html

:)

1 Like

Ohhhh, silly mistake. I just learned about arrays so Iā€™m not too familiar with them yet. Thanks for the reply, I was really worried that the problem was a bigger issue.