2D简单球碰撞矢量 [英] 2D simple ball collision vector
问题描述
试图使两个球碰撞并以适当的角度反弹。
当球碰撞但它们粘在一起时,我不知道我在这里做错了什么。
Trying to get two balls to collide and bounce back at appropriate angles. When the balls collide however they get stuck together and I have no idea what I'm doing wrong here.
我称此为<$ c $我的动画函数
中的c> checkCollision()函数显然 cx
是ball1 xpos
, cx2
是ball2 xpos
。与 cy
相同。
I'm calling this checkCollision()
function within my animate function
Obviously cx
is ball1 xpos
, cx2
is ball2 xpos
. Same for cy
.
function checkCollision () {
var dx = cx2 - cx; // distance between x
var dy = cy2 - cy; // distance between y
var distance = Math.sqrt(dx * dx + dy * dy);
if (distance < (radius1 + radius2)) {
// Collision detected. Find the normal.
var normalX = dx / distance;
var normalY = dy / distance;
//find the middle point of the distance
var midpointX = (cx + cx2)/2;
var midpointY = (cy + cy2)/2;
//bounce back
cx = midpointX - radius1*normalX;
cy = midpointY - radius1*normalY;
cx2 = midpointX - radius2*normalX;
cy2 = midpointY - radius2*normalY;
var dVector = (vx - vx2) * normalX;
dVector += (vy - vy2) * normalY;
var dvx = dVector * normalX;
var dvy = dVector * normalY;
vx -= dvx;
vy -= dvy;
vx2 += dvx;
vy2 += dvy;
}
...
我从未做过很多事工作。有没有更简单的方法可以做到这一点?
我该如何用角度写呢?
I've never done much/any vector work. Is there any easier way to do this? How would I write this with angles instead?
推荐答案
您需要使用一些基本的数学方法来检测之间的交集两个圆圈。
You need to use some basic maths to detect the intersection between two circles.
此处描述了类似的问题:
A similar problem is described here:
algorithm to detect if a Circles intersect with any other circle in the same plane
有一个C#示例可以轻松地适应Javascript。
There is a C# sample that could be easily adapted to Javascript.
这篇关于2D简单球碰撞矢量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!