How can I add motion to a masked p5.js vertex object within a class?

38 Views Asked by At

I am a beginner coder and am trying to create a p5.js for an assessment piece. I have created this car shape using the vertex() function and have placed a mask over it. I would like to have the car move across the x-axis as though it is driving across the screen. How do I go about doing this?

Here is the link to my sketch: https://editor.p5js.org/viviannaleman/sketches/XmeMeOq_Y

I have tried to update the x-position of the car's vertices using an If statement (if x > width, x =+ 1) (Here is a link to an example of what I'm trying to achieve: https://editor.p5js.org/ri1/sketches/Hk5piJg14). However it appears to not work because of the mask I've placed on top of the object.

Is there a way around this?

Thank you in advance!

1

There are 1 best solutions below

1
BobSfougaroudis On
class Car {
  constructor(x, y, carPos, carFill, carShape, carSong, micLevel, mic, amp) {
    this.x = x;
    this.y = y;
    this.carPos = createVector(this.x, this.y);
    this.carFill = carFill;
    this.carShape = carShape;
    this.carSong = carSong;
    this.mic = mic;
    this.amp = amp;
  }

  updateCar() {
    this.x += 1;
    if (this.x >= width) {
      this.x = -400;
    }
    this.carPos.x = this.x;
  }

  showCar() {
    push();
    translate(this.carPos);
    noLoop();

    this.carShape.beginShape();
    this.carShape.vertex(130, 130);
    this.carShape.vertex(145, 95);
    this.carShape.vertex(170, 80);
    this.carShape.vertex(230, 80);
    this.carShape.vertex(285, 0);
    this.carShape.vertex(305, 5);
    this.carShape.vertex(525, 15);
    this.carShape.vertex(570, 40);
    this.carShape.vertex(595, 80);
    this.carShape.vertex(660, 85);
    this.carShape.vertex(700, 110);
    this.carShape.vertex(710, 130);
    this.carShape.vertex(695, 160);
    this.carShape.vertex(160, 160);

    // Draw wheels
    this.carShape.circle(310, 170, 90);
    this.carShape.circle(510, 170, 90);

    this.carShape.endShape(CLOSE);

    this.carFill.mask(this.carShape);
    image(this.carFill, 0, 0, width, height);

    this.carSong.loop();
    this.carSong.setVolume(0.1);
    
    pop();
  }
}

as u use in the class of car some constructor and show of the car I suggest you use a new method called update which moves the car by updating its cordinates (by little) and then show the car again. And you shoud call updateCar inside your draw code