我有一个非常有趣的任务,可能有人可以提出更好的算法。
我们有一个球,它通过以下参数单独移动:
- 速度
- 航向(从定义的东/西移动的角度如 90/180/270/360 度)
球已经定义了速度、头球和间隔的列表,之后他必须采取下一个速度和头球。
我试图在 JavaScript 中实现这一点,但确实卡住了。例如:
function go(ball, element) {
let speed = element.speed;
let heading = ball.heading;
ball.roll(speed, heading); // this function makes just one coup
}
Main 函数适用于元素列表(例如):
[
{
"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
}
]
作为第一个想法的主要功能:
function startRolling (elements) {
for (var element of elements) {
let distance = element.distance;
var timerId = setInterval(() => go(bolt, element), distance * 1000);
setTimeout(() => {
clearInterval(timerId)
}, distance);
}
}
我不是 JavaScript 方面的专家,我知道如何在 Java 中实现这一点,但在 JavaScript 中找不到解决方案。有人可以帮我吗?
回答1
你也可以像这样构造它,其中每个球都是一个对象,stores 有它自己的速度并封装了它自己的“go”逻辑。然后,您将其作为 Ball 对象的列表/数组进行管理,并定期对其调用 go、draw、update 等方法进行迭代。
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;
}
}