xxxxxxxxxx
101
// Create an array to store a whole lot of movers
let movers = [];
function setup() {
createCanvas(windowWidth, windowHeight);
angleMode(DEGREES);
// Specify your moves here
let moves = [{
sf: 30, // start frame of movement
ef: 240, // end frame of movement
speed: 0.67, // overall speed of movement
a: 90, // angle of movement
f: 0 // facing relative to angle of movement
},
{
sf: 320,
ef: 440,
speed: 4,
a: 220,
f: 180
},
]
// Ad the mover
movers.push(new Mover(width / 2, height / 2, 90, moves));
}
function draw() {
background(220);
// Loop through all of the movers
for (let mover of movers) {
// Update each of them
mover.update();
// Display each of them
mover.display();
}
}
// Define the Mover class
class Mover {
// Movers have x,y position
// xpseed and yspeed for speed and direction of movement
// start frame (sf) and end frame (ef) for timing
constructor(x, y, a, moves) {
this.x = x;
this.y = y;
this.a = a;
this.f = a;
this.moves = moves;
// Get things going
this.m = 0;
this.next();
}
next() {
let move = this.moves[this.m];
this.msf = move.sf;
this.mef = move.ef;
this.a = move.a;
this.f = move.f;
// Calculate xspeed, yspeed based on angle and speed
this.xspeed = cos(this.a) * move.speed;
this.yspeed = sin(this.a) * move.speed;
// Advance if we haven't reached the end yet.
if (this.m < this.moves.length - 1) {
this.m++;
// Grab the "next move start frame" (nmsf)
this.nsf = this.moves[this.m].sf;
}
}
// Update the mover's position when it's time to move
update() {
// Move
if (frameCount > this.msf && frameCount < this.mef) {
this.x += this.xspeed;
this.y += this.yspeed;
}
// Check to see if it's time to do next move
if (frameCount > this.nsf) this.next();
}
// Display the mover
display() {
strokeWeight(10);
point(this.x, this.y);
let R = 10;
let x = cos(this.a + this.f) * R + this.x;
let y = sin(this.a + this.f) * R + this.y;
strokeWeight(5);
point(x, y);
}
}