I'm trying to animate an array of circles using HTML canvas. I also try to save the circle's previous information in order to be able to determin the velocity vectors for later use. However i can't seem to save the previous circles in a global variable. Logging out the circle array and the previous array gives back the same values even if the circle's position changed.
class Vector {
constructor(x, y) {
this.x = x;
this.y = y;
}
static subst(vector1, vector2){
return new Vector(vector1.x - vector2.x, vector1.y - vector2.y)
}
static divd(vector, scalar){
return new Vector(vector.x/scalar,vector.y/scalar)
}
}
class Circle {
constructor(x,y, radius,color,isGrabbed) {
this.pos = new Vector(x,y)
this.radius = radius;
this.color = color;
this.velocity = new Vector(0,0);
this.isGrabbed = isGrabbed;
}
draw(ctx){
ctx.beginPath();
ctx.arc(this.pos.x, this.pos.y, this.radius, 0, Math.PI*2)
ctx.fillStyle = this.color;
ctx.fill()
}
update(prevPos){
this.velocity = Vector.subst(this.pos, prevPos)
console.log(this.velocity)
}
}
let circles = []
circles.push(new Circle(300, 400, 70, "red", false))
circles.push(new Circle(500, 300, 70, "green", false))
circles.push(new Circle(800, 600, 70, "yellow", false))
let previous = [] // variable for the previous circle array
function update(){
ctx.clearRect(0,0, canvas.width, canvas.height)
// iterating through the array of circles and drawing them onto the canvas
for(let i = 0; i< circles.length; i++){
circles[i].pos.x +=10; // changes the circle's x-position on every animation frame
if(previous.length>0){
circles[i].update(previous[i].pos)
console.log(previous[i].pos.x,circles[i].pos.x) // both values are the same
}
}
// saving the previous array of circles
for(let i = 0; i< circles.length; i++){
previous[i] = circles[i]
}
requestAnimationFrame(update)
}