I have very interesting task, might be someone can propose better algorithm.
We have a ball, which moves alone by the next parameters:
The ball have defined list of speed, heading and interval, after which he have to take the next speed and heading.
I'm trying to implement this in JavaScript, but really stuck. For example:
function go(ball, element) {
let speed = element.speed;
let heading = ball.heading;
ball.roll(speed, heading); // this function makes just one coup
}
Main function works with a list of elements (for example):
[
{
"point": 1,
"heading": 90, //angle
"speed": 50,
"duration": 30 //duration
},
{
"point": 2,
"heading": 180, //angle
"speed": 50,
"duration": 6 //duration
},
{
"point": 3,
"heading": 270, //angle
"speed": 50,
"duration": 3 //seconds
}
]
Main function as a first idee:
function startRolling (elements) {
for (var element of elements) {
let distance = element.distance;
var timerId = setInterval(() => go(bolt, element), distance * 1000);
setTimeout(() => {
clearInterval(timerId)
}, distance);
}
}
I'm not a big an expert in JavaScript, I know how to implement this in Java, but cannot find solution in JavaScript. Could someone please help me?
You could also structure it something like this, where each ball is an object, stores its own velocity and encapsulates its own "go" logic. You then manage it as a list/array of Ball objects, iterating through it calling their go, draw, update, whatever, methods at regular intervals.
class Vector {
constructor(x, y) {
this.x = x;
this.y = y;
}
}
class Ball {
constructor(x, y) {
this.pos = new Vector(x, y);
this.vel = new Vector(/* some random numbers here */);
}
go() {
this.pos.x += this.vel.x;
this.pos.y += this.vel.y;
}
}