Does anyone know why the bolded line of code is giving me a null pointer exception?

`float level=1;
float playerx=394;
float playery=435;
float playerDeltax=0;
float playerDeltay=0;




void setup() {
  size(800, 800);
}
void draw() {
  //intro
  if (level==1) {
    background(0, 0, 0);
    textSize(65);
    fill(255, 255, 255);
    text("HELLO", 307, 170);
    textSize(40);
    text("Welcome to a rip-off version of red ball", 16, 261);
    //makes the cringey red ball eyes
    fill(255, 255, 255);
    ellipse(355, 407, 50, 50);
    ellipse(427, 407, 50, 50);
    fill(0, 0, 0);
    ellipse(355, 407, 30, 30);
    ellipse(427, 407, 30, 30);
    //writes the continue text
    fill(255, 255, 255);
    text("Use W,S,A,D to move", 130, 711);
  }
  //if the player goes too far right on level 1
  if (playerx>800) {
    level=2;
    playerx=50;
  }
  if (playerx<0) {
    level=1;
    playerx=350;
  }

  playerx=playerx+playerDeltax;
  playery=playery+playerDeltay;
  println(mouseX + ", " + mouseY);
}
{
  //level 2
  if (level==2) {
  }
}{
if(level!=3){
   **fill(255, 0, 0);**
    ellipse(playerx, playery, 150, 150);
}}
//dictates the movement
void keyPressed() {
  if (key=='a') {
    playerDeltax=-5;
  }
  if (key=='d') {
    playerDeltax=5;
  }
  if (key=='s') {
    playerDeltay=5;
  }
  if (key=='w') {
    playerDeltay=-5;
  }
}


void keyReleased() {
  if (key=='a') {
    playerDeltax=0;
  }
  if (key=='d') {
    playerDeltax=0;
  }
  if (key=='s') {
    playerDeltay=0;
  }
  if (key=='w') {
    playerDeltay=0;
  }
}`
Tagged:

Answers

  • Fixing your formatting would make it more obvious what's going on. Hint: when does the draw() function end?

    You're putting code inside { } curly braces outside of a function, which are called initializer blocks. These are used for initializing variables before any other code has been run.

    The problem is that you're calling the fill() function in your initializer block. But since it's running before any other code, your sketch has not yet been initialized.

    Basically, you need to get rid of the initializer blocks and move that code back inside a function.

Sign In or Register to comment.