我正试图使用两个球在JavaScript中进行碰撞检测和处理。我可以检测到球与画布的边界碰撞并且可以让它们反弹回来,我可以判断球何时相互碰撞,但是我不能让它们相互反弹。
我现在所拥有的:
$(document).ready(function() {
var canvas = $("#myCanvas");
var context = canvas.get(0).getContext("2d");
var canvasWidth = canvas.width();
var canvasHeight = canvas.height();
ball1 = new Ball(30),
ball2 = new Ball(30),
angle1 = 25,
angle2 = 47,
speed = 3,
ball1.x = 200,
ball1.y = 240,
ball2.x = 100,
ball2.y = 240,
flag = false,
vx1 = speed*Math.cos(angle1*Math.PI/180);
vy1 = speed*Math.sin(angle1*Math.PI/180);
vx2 = speed*Math.cos(angle2*Math.PI/180);
vy2 = speed*Math.sin(angle2*Math.PI/180);
(function animate () {
context.clearRect(0, 0, canvasWidth, canvasHeight);
window.requestAnimationFrame(animate, canvas);
if(ball1.x > canvasWidth - ball1.radius || ball1.x < 0 + ball1.radius) {
vx1 = -vx1;
}
if(ball1.y > canvasHeight - ball1.radius || ball1.y < 0 + ball1.radius) {
vy1 = -vy1;
}
if(ball2.x > canvasWidth - ball2.radius || ball2.x < 0 + ball2.radius) {
vx2 = -vx2;
}
if(ball2.y > canvasHeight - ball2.radius || ball2.y < 0 + ball2.radius) {
vy2 = -vy2;
}
ball1.x +=vx1;
ball1.y +=vy1;
ball2.x +=vx2;
ball2.y +=vy2;
dist = calcDistance(ball1.x, ball1.y, ball2.x, ball2.y);
if(dist < (ball1.radius + ball2.radius)) {
flag = true;
}
if(flag) {
document.getElementById("dist").innerHTML = "collision!";
//Where collision handling of balls should go
flag = false;
}
else {
document.getElementById("dist").innerHTML = "";
}
ball1.draw(context);
ball2.draw(context);
function calcDistance(x1, y1, x2, y2) {
var dx = x1 - x2;
var dy = y1 - y2;
var distance = Math.round(Math.sqrt(dx*dx + dy*dy));
return distance;
};
}());
});
我已经看过这个问题Ball to Ball Collision - Detection and Handling,但我认为可能有一种更简单的方法可以做到这一点,因为我已经可以检测到碰撞发生的时间,这只是处理我没有做过的事情。 #39;但我通过将if(flag)语句更改为:
来解决这个问题if(flag) {
document.getElementById("dist").innerHTML = "collision!";
vx1 = -vx1;
vy1 = -vy1;
vx2 = -vx2;
vy2 = -vy2;
flag = false;
}