Javascript 2数组冲突检测

时间:2015-12-19 19:48:19

标签: javascript arrays html5

我正在使用html5画布和IE 11进行游戏并拥有2个阵列:

var bodies = [];
var bullets = [];

body数组存储玩家和敌人,而子弹阵列存储子弹。我在需要时使用对象构造函数添加新对象。我希望玩家在与敌人接触时消失。 我正在尝试这个:

for (i=0; i<bodies.length; i++) {
  //I add 30 to the x value because all bodies are 30px long
  if (bodies[i].x + 30 == player.x) {
    bodies.splice(0, 1);
    //the player is always in the 0 spot in the array
  }
}

然而,这不起作用,并且敌人穿过玩家。有更好的方法吗?我感谢任何帮助。

3 个答案:

答案 0 :(得分:0)

当子弹的位置(x,y)在敌人体内(x,y)时发生碰撞但你的位置比较没有进行这种空间感知检查。此外,你的问题并不是说明子弹是否涉及或只是身体与身体(球员/敌人)的位置碰撞。

这引入了对这种位置重叠的检查:

if (player.x >= bodies[i].x  &&
    player.x <= bodies[i].x + 30 ) {

    bodies.splice(0, 1);
    //the player is always in the 0 spot in the array
}

我猜你正在解决一维世界,因此只是x ...很酷开始简单然后扩展...一旦解决然后扩展到2D(x,y)或3D(x,y, z)或甚至ND通过将这些额外的维度包含在类似的边界比较中,就像你只有x

一样

答案 1 :(得分:0)

也许这种情况(body [i] .x + 30 == player.x)永远不会成立。为了移动玩家和敌人你为他们增加了速度,不是吗?所以,那个速度肯定大于1(比方说2)。所以,在某一时刻,它会发生,例如,body [i] .x + 30 = 99和player.x = 100,以及下一个时刻,在添加&#34; 2&#34;对于body [i] .x,你以body [i] .x + 30 = 101和player.x = 100结尾。

而不是那个条件(bodies [i] .x + 30 == player.x),尝试检查body [i]和玩家是否与以下条件重叠:

if(bodies [i] .x&gt; player.x&amp;&amp; bodies [i] .x + 30&lt; = player.x){...}

答案 2 :(得分:0)

我使用此方法进行碰撞检测:

// **isColliding()** returns true if two passed bodies are colliding.
// The approach is to test for five situations.  If any are true,
// the bodies are definitely not colliding. If none of them
// are true, the bodies are colliding.
// 1. b1 is the same body as b2.
// 2. Right of `b1` is to the left of the left of `b2`.
// 3. Bottom of `b1` is above the top of `b2`.
// 4. Left of `b1` is to the right of the right of `b2`.
// 5. Top of `b1` is below the bottom of `b2`.
function isColliding(b1, b2) {
    return !(
        b1 === b2 ||
        b1.x + b1.width < b2.x - b2.width ||
        b1.y + b1.height < b2.y - b2.height ||
        b1.x - b1.width > b2.x + b2.width ||
        b1.y - b1.height > b2.y + b2.height
    );
}

来自Mary live-codes a JavaScript game from scratch – Mary Rose Cook at Front-Trends 2014