【发布时间】:2018-10-01 07:02:38
【问题描述】:
我有两个圆圈围绕圆圈旋转,我希望圆圈在经过一圈后随机改变速度。两个圆圈的速度应该不同,或者它们可能是相同的速度(然后会发生碰撞)。例如,在第一次运行期间,两个圆都以 10m/s 的速度移动,当它到达旋转结束后,它们会发生碰撞。假设在旋转之后,它将圆 1 变为 15m/s,圆 2 变为 30m/s,那么它们就不会发生碰撞。我想知道如何实现这一点。这只是我想要实现的一个想法。如果每转后速度随机化就更好了。
任何帮助将不胜感激。
代码:
(function() {
var ctx = document.getElementById("canvas").getContext("2d"),
x1 = 160,
y1 = 120,
x2 = 330,
y2 = 280,
radius = 20;
angle = 0,
velX = 0,
velY = 0,
thrust = 3,
rotation = 0;
function draw() {
velX = Math.cos(angle * Math.PI / 180) * thrust;
velY = Math.sin(angle * Math.PI / 180) * thrust;
x1 += velX;
y1 += velY;
angle += 1;
ctx.fillStyle = "#000";
ctx.clearRect(0, 0, 550, 400);
ctx.beginPath();
ctx.arc(x1, y1, radius, 0, Math.PI * 2);
ctx.closePath();
ctx.fill();
draw2();
setTimeout(function() {
draw()
}, 30);
}
function draw2() {
velX = Math.cos(angle * Math.PI / 180) * thrust;
velY = Math.sin(angle * Math.PI / 180) * thrust;
x2 += -velX;
y2 += -velY;
angle += 1;
ctx.fillStyle = "#80ced6";
ctx.beginPath();
ctx.arc(x2, y2, radius, 0, Math.PI * 2);
ctx.closePath();
ctx.fill();
collisiondetection();
}
var distance = 0;
var totalcounter = 0;
var collide = false;
function collisiondetection() {
distance = Math.sqrt((x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2));
if (distance < radius * 2) {
if (collide == false) {
totalcounter = totalcounter + 1;
document.getElementById("cTotal").innerHTML = "Total collisions:" + totalcounter;
collide = true;
}
} else {
collide = false;
}
}
draw();
})();
<canvas id="canvas" width="550" height="400" style="background:#eee;"></canvas>
<span id="cTotal">Total collisions: </span>
【问题讨论】:
-
欢迎。你应该展示你的代码并告诉我们它到底有什么问题,并且没有按你的意愿工作。
-
怎么样。
Math.floor(Math.random() * 101); // returns a random integer from 0 to 100?旋转后只需生成一个随机的speed数字。 -
只需声明一个可变速度并使其随机,并将值发送到
setTimeout(function(){draw()}, speed) -
我不听你的解释
-
我尝试了您关于声明速度变量并使其随机化的建议。问题是这两个圈子在每次革命中总是“碰撞”。这个想法是两个圆圈在不同的旋转中具有不同的速度,因此它们可能会发生碰撞或不会发生碰撞。我希望我说得通
标签: javascript html random settimeout