两个精灵相撞 - 一个后方结束了另一个?

时间:2015-01-21 14:10:12

标签: javascript collision-detection collision

我正在编写一个简单的游戏(在Javascript中),其中圆形精灵可以相互碰撞。我存储一个角度(以度为单位)和每个对象的x,y。我有碰撞检测工作,但我需要找出哪个精灵击中另一个。因此,对于两个物体相撞而哪一个物体驱动到另一个物体中(即,其中一个精灵的前部与另一个的“非前部”接触)。或者用另一种方式,一个后方结束另一个。在非常接近事故的情况下,例如如果它们在碰撞(180度碰撞)上或者在5度内(175-185度碰撞)之间形成一个绝对直接的头部,那么我需要发现这一点并且不对任何一个精灵赋予“责备”。数学,或者更好的代码是什么呢?

     var angleA = Math.abs(collidedWith.angle - 180);
     var angleB = Math.abs(this.angle - 180);
     var angleConsideredHeadOn = 5;
     var anglesSubtracted = Math.abs(angleA - angleB);

     if (anglesSubtracted < angleConsideredHeadOn) {
         var headOn = true;
     }


     if (anglesSubtracted >= angleConsideredHeadOn) {
         // There was a non-head on crash

         var xA = collidedWith.velocityX;
         var yA = collidedWith.velocityY;
         var xB = this.velocityX;
         var yB = this.velocityY;
         // Need to determine which sprites 'front' collided with the other's side or read
     }

2 个答案:

答案 0 :(得分:0)

要检测正面情况,请取两个(预碰撞)速度矢量的点积,这将给出它们标题之间的余弦。如果该值小于-0.9 Pi,那么碰撞就会继续进行。

否则,责备的精灵是具有最高绝对速度的精灵(因为慢速精灵不可能追尾快速精灵)。

答案 1 :(得分:0)

这似乎有用......

// Javascript
// Two objects 'this' and 'collidedWith' have collided
// this code determines who head butted the other
// Based on having an angle and an X and Y velocity (xDir and yDir) where volicity could be negative (going left or up) or positive (going right or down)
// 'degrees' is a function which converts radians to degrees

var angleConsideredHeadOn = 15;

var theta_a = degrees(Math.atan2(this.xDir, this.yDir));
var theta_b = degrees(Math.atan2(collidedWith.xDir, collidedWith.yDir));

var a_to_b = degrees(Math.atan2(this.posY - collidedWith.posY, this.posX - collidedWith.posX)); // Normal angle from 'this's perspective
var b_to_a = -a_to_b % 360; // ditto from collidedWith's perspective

var collision_angle_a = Math.abs(theta_a - a_to_b) % 360
var collision_angle_b = Math.abs(theta_b - b_to_a) % 360

// Collision is close to head on
if (Math.abs(collision_angle_a - collision_angle_b) < angleConsideredHeadOn) return;

// 
if (collision_angle_a < collision_angle_b) {

    // 'collidedWith' head butted the other object

} else {

    // 'this' head butted the other object

}