Search code examples
javascriptprocessingp5.js

Why am I getting NaN for integer?


This is my code:

function setup() {
  createCanvas(windowWidth, windowHeight);
  noStroke();
}

var momentum = [0, 0]; //x and y speed
var pos = [650, 300]; //player x and y
var enemiesX = []; //enemies x's
var enemiesY = []; //enemies y's

function draw() {
  background(200);
  momentum[0] = (pos[0] - mouseX) / 5;
  pos[0] =+ momentum;
  fill(115);
  ellipse(pos[0], pos[1], 30, 30);
  text(pos[0] + ", " + pos[1], 20, 20);
}

I am using arrays to compact similar x's and y's that are paired. I was testing with the text function, and I realized the first of every array is NaN. I know its this:

  momentum[0] = (pos[0] - mouseX) / 5;
  pos[0] =+ momentum;

but what is wrong?

Also, before people spam this with flags saying its a duplicate, the simplicity means no other question of this nature had a relevant answer.


Solution

  • There are two issues with your code. The first is that you're using =+ instead of +=. The second is that momentum is an array, not a number. This is what your code is doing right now in the two lines you highlighted:

    • Evaluate (pos[0] - mouseX) / 5
    • Save that value in the 0 position of the momentum array.
    • Evaluate +momentum
    • Save that value in the 0 position of the pos array.

    At the third bullet point, what happens is that +momentum evaluates to NaN. Then you're saving that value in the pos array. The first of the two lines is fine. I think that what you're looking to do is to add momentum[0] to pos[0], which can be done like this:

      pos[0] += momentum[0];
    

    I'm not certain what you intend, but my guess is that you want to make the circle go toward the cursor, not away from it. In that case, you have the sign of the momentum wrong, it should be like this:

      momentum[0] = (mouseX - pos[0]) / 5;
      pos[0] += momentum[0];