xxxxxxxxxx
54
class Mover {
constructor(startingPosition, startingVelocity, speedLimit, size, sprite) {
this.position = startingPosition;
this.velocity = startingVelocity;
this.speedLimit = speedLimit;
this.size = size;
this.sprite = sprite;
}
// Add the mover's velocity to its position.
update() {
// Calculate the distance (delta) to the mouse.
let mouse = createVector(mouseX, mouseY);
let delta = p5.Vector.sub(mouse, this.position);
// Scale down the directional delta by 100.
delta.div(100);
this.acceleration = delta;
// Acceleration changes the mover's velocity.
this.velocity.add(this.acceleration);
// Mover has a maximum speed.
this.velocity.limit(this.speedLimit);
// Velocity changes the mover's position.
this.position.add(this.velocity);
}
// Display the mover as circle at its current position.
display() {
push();
stroke(0);
fill(175);
translate(this.position.x, this.position.y);
// If any key is pressed draw a "nose" indicating the
// direction of the velocity.
if (keyIsPressed) {
let noseLength = map(this.velocity.mag(), 0, this.speedLimit, 0, this.size * 2);
let direction = this.velocity.copy().setMag(noseLength);
line(0, 0, direction.x, direction.y);
}
// Using arc tan to find velocity's angle of rotation.
let heading = atan2(this.velocity.y, this.velocity.x);
// Rotate a 90 degrees counter-clockwise because sprites face "up".
rotate(heading + PI/2);
image(this.sprite, 0, 0);
pop();
}
}