I have some triangles on canvas and they are randomly moving around the canvas according to given velocity. It is similar to this exercise but triangles instead of circles.
draw(){
ctx.fillStyle="white";
const angle = Math.atan2(this.velY,this.velX);
ctx.save();
ctx.translate(this.x,this.y);
ctx.rotate(angle);
ctx.restore();
ctx.beginPath();
ctx.moveTo(this.x,this.y);
ctx.lineTo(this.x+10,this.y+10);
ctx.lineTo(this.x-10,this.y+10);
ctx.fill();
}
I tried this and it's having no effect whatsoever
here's how I am using the function
while(boids.length < 250){
boid = new Boid(
random(10,canvas.width-10),
random(10,canvas.height-10),
random(-5,5),
random(-5,5)
)
boids.push(boid);
}
function animate(){
ctx.fillStyle = "rgb(17 17 17)";
ctx.fillRect(0,0,canvas.width,canvas.height);
for(const boid of boids){
boid.draw();
}
requestAnimationFrame(animate);
}
boid is a class with members, x,y,velX,velY.
You could try drawing triangles without using rotate or translate...
Just a bit of trigonometry math:
On this case I'm using equilateral triangles, but you can use any others once you play around with the math, if it confuses you might want to start here:
https://study.com/skill/learn/how-to-inscribe-an-equilateral-triangle-in-a-circle-explanation.html
If you insist on using rotate and translate, here is an example:
My approach here is to translate and rotate then draw our triangle right at that position then undo the rotation and translate to go back to the starting position, you can see that I'm drawing four triangles with different angles and they are spaced at an increment of 20 on the X axis.