使用角度的弹性2d球碰撞

时间:2015-05-28 04:30:12

标签: javascript canvas

是的,这里有几个主题,但使用角度并不多,我真的想通过这种方式解决这个问题, 我现在坚持为圆圈设置新的速度角度。我一直在看: http://www.hoomanr.com/Demos/Elastic2/ 作为对它的参考,但我现在被卡住了。

任何人都能解释一下吗?

对于球1和球2,

cx / cy / cx2 / cy2 =中心x / y。 vx / vy / vx2 / vy2 =球1和2的x / y速度

function checkCollision() {
var dx = cx2 - cx;  //distance between x
var dy = cy2 - cy;  // distance between y
var distance = Math.sqrt(dx * dx + dy * dy);

var ang = Math.atan2(cy - cy2, cx - cx2);

// was displaying these in a div to check
var d1 = Math.atan2(vx, vy); //ball 1 direction
var d2 = Math.atan2(vx2, vy2); //ball 2 direction

// this is where I am stuck, and i've worked out this is completely wrong now
// how do i set up the new velocities for 
var newvx = vx * Math.cos(d1 - ang);
var newvy = vy * Math.sin(d1 - ang);
var newvx2 = vx2 * Math.cos(d2 - ang); 
var newvy2 = vy2 * Math.sin(d2 - ang);


if (distance <= (radius1 + radius2)) {
    //Set new velocity angles here at collision..
}

这是一个代码链接:

http://codepen.io/anon/pen/MwbMxX

1 个答案:

答案 0 :(得分:3)

几个方向:

•如评论中所述,仅使用弧度(不超过* 180 / PI) •atan2将y作为第一个参数,x作为第二个参数。

var d1 = Math.atan2(vy, vx); //ball 1 direction in angles
var d2 = Math.atan2(vy2, vx2); //ball 2 direction in angles

•旋转矢量,首先计算其范数,然后仅使用新角度投影:

var v1 = Math.sqrt(vx*vx+vy*vy);
var v2 = Math.sqrt(vx2*vx2+vy2*vy2);

var newvx = v1 * Math.cos(d1 - ang);
var newvy = v1 * Math.sin(d1 - ang);
var newvx2 = v2 * Math.cos(d2 - ang); 
var newvy2 = v2 * Math.sin(d2 - ang);

•您正在检测碰撞已经发生,因此两个圆都重叠,但您 NOT 解决了碰撞,这意味着圆圈在下次迭代时可能仍会重叠,从而导致新的碰撞和一个新的方向,......没有解决,等等。 - &GT;&GT;解决碰撞后,您需要确保两个圆圈不再发生碰撞。

•最后一个问题,但不是一个小问题,是你计算角度的方法。再也没有时间对不起了,但是对于你和我们来说,构建一个(几个)方案来展示你如何计算角度会很有帮助。

此处更新(但不能正常工作)codepen:

http://codepen.io/anon/pen/eNgmaY

祝你好运。

编辑:

您在codepen.io/anon/pen/oXZvoe的代码简化了这一点:

 var  angle = Math.atan2(dy, dx),
      spread = minDistance - distance,
      ax = spread * Math.cos(angle),
      ay = spread * Math.sin(angle);

    vx -= ax;
    vy -= ay;
    vx2 += ax;
    vy2 += ay;

你正在从速度中减去两个圆圈之间的差距。由于之后您将速度添加到位置,这将进行空间分离(=>不再发生碰撞) 我想要理解vx- = ax意味着什么,我们必须记住牛顿:v = a * t,其中a是加速度,所以基本上做vx = -ax意味着施加一个力,两个中心之间的方向作为方向,并且两个圆圈作为强度碰撞(扩散)的量。这个数量显然是随机的,因此您看到的数值不稳定性:有时效果很小,有时候很大。

在这里查看恒定打孔版本:

http://codepen.io/anon/pen/WvpjeK

var angle = Math.atan2(dy, dx),
  spread = minDistance - distance,
  ax = spread * Math.cos(angle),
  ay = spread * Math.sin(angle);

// solve collision (separation)
cx -= ax;
cy -= ay;

// give a punch to the speed
var punch = 2;

vx -= punch*Math.cos(angle);
vy -= punch*Math.sin(angle);
vx2 += punch*Math.cos(angle);
vy2 += punch*Math.sin(angle);
相关问题