add more vector methods and asteroid path node generation

master
Milan Suman 2022-07-27 00:06:10 +05:30
parent 73120c9326
commit 1a69f86e4a
1 changed files with 23 additions and 2 deletions

View File

@ -11,7 +11,7 @@ class Vector{
} }
magnitude(){ magnitude(){
return Math.sqrt(this.x^2 + this.y^2); return Math.sqrt(this.x**2 + this.y**2);
} }
//vector product would be useless because the resultant would be in the z-axis //vector product would be useless because the resultant would be in the z-axis
@ -20,18 +20,35 @@ class Vector{
//cosθ = a.b/|a||b| //cosθ = a.b/|a||b|
return Math.acos(this.scalarProduct(other)/(this.magnitude()*other.magnitude())); return Math.acos(this.scalarProduct(other)/(this.magnitude()*other.magnitude()));
} }
//figuring out coordinates from angle and distance
positionFromAngle(angle, distance){
return new Vector((this.x + distance) * Math.cos(angle), (this.y+distance)*Math.sin(angle));
}
} }
class Asteroid{ class Asteroid{
//FIXME: Asteroid generation is very wonky
constructor(size, position, edges=5){ constructor(size, position, edges=5){
this.size = size; this.size = size;
this.edges = edges; this.edges = edges;
this.position = position; this.position = position;
this.nodes = [this.position];
for(let i=0; i<this.edges; i++){
let pos = this.nodes[i].positionFromAngle( this.nodes[i].angle() + (Math.max(Math.PI/6, Math.random()*(Math.PI/3))), 5);
this.nodes.push(pos);
}
} }
draw(ctx){ draw(ctx){
ctx.beginPath(); ctx.beginPath();
this.nodes.forEach((node, _) => {
ctx.lineTo(node.x,node.y);
})
ctx.closePath();
ctx.stroke();
} }
} }
@ -43,8 +60,12 @@ canvas.height = window.innerHeight;
const ctx = canvas.getContext("2d"); const ctx = canvas.getContext("2d");
const asteroid = new Asteroid(50, new Vector(300, 240));
function animate(){ function animate(){
requestAnimationFrame(animate); requestAnimationFrame(animate);
ctx.clearRect(0, 0, canvas.width, canvas.height);
asteroid.draw(ctx);
} }
animate(); animate();