Cannot read property 'x' of undefined. Problem reading parameters of vector

Hello everybody, this is my first post so I hope everything is correct.

I’m having trouble with the function pathFunction() (towards the end). What I want to do is to store the vector this.pos in the array “path” and then paint all of the positions, so the path is drawn. The problem is that it only paints the last point. Here is a link to the game so you can test the code yourself. Any help is appreciated. Thanks: p5.js Web Editor

class Ship {
  constructor() {
    this.acc = new p5.Vector(0, 0.4);
    this.vel = new p5.Vector(0, 0);
    this.pos = new p5.Vector(0, -40);
    this.state = "";
    this.path = [];
    this.path[0] = this.pos;
  }

  move() {
    if (keyIsDown(LEFT_ARROW)) {
      this.acc.rotate(alpha);
    } else if (keyIsDown(RIGHT_ARROW)) {
      this.acc.rotate(-alpha);
    }
    if (keyIsDown(UP_ARROW)) {
      this.state = "moving";
      this.vel.add(this.acc);
      this.vel.limit(6);
    } else {
      this.state = "";
      this.vel.mult(0.99);
    }
    this.pos.add(this.vel);
  }

  draw() {
    push();
    translate(this.pos.x, this.pos.y);
    rotate(this.acc.heading() - HALF_PI);
    stroke(255);
    noFill();
    beginShape();
    vertex(0, 15);
    vertex(-10, -10);
    vertex(0, -5);
    vertex(10, -10);
    endShape(CLOSE);
    //Dibujar llama
    if (this.state == "moving") {
      beginShape();
      vertex(-6, -8);
      vertex(0, -15);
      vertex(6, -8);
      endShape();
    }
    pop();
  }

  pathFunction() {
    this.path.push(this.pos);
    stroke("red");
    strokeWeight(4);
    for (var i = 0; i < this.path.length; i++) {
      point(this.path[i].x, this.path[i].y);
    }
  }

  update() {
    this.move();
    this.draw();
    this.pathFunction();
  }
}

The issue is that when you push this.pos into your path array you’re always storing a reference to the same object, and when you update a vector with the add function it mutates the vector object. So what you’re winding up with is a big array of the same vector over and over again. You’ll want to call the copy function on the pos vector when adding it to the path array. Also, you’re going to want to limit the length of the path array because otherwise your game will use progressively more and more memory and the draw function will slow down considerably over time.

Working example: p5.js Web Editor

2 Likes

Thank you very much! And yes, I plan to limit the for loop for that exact reason. :grinning: