Javascript 2阵列冲突检测
Javascript 2 arrays collision detection
我正在用html5画布和IE 11制作一个游戏,有两个数组:
var bodies = [];
var bullets = [];
身体阵列存储玩家和敌人,而子弹阵列存储子弹。我使用对象构造函数在需要的时候添加新对象。我希望玩家在接触敌人时消失。我正在尝试这个:
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
}
}
然而,这不起作用,敌人穿过玩家。有更好的方法吗?我感谢你的帮助。
当子弹的位置(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 进行比较一样
也许这个条件(body[i].x+30==player.x)永远不会成立。为了移动玩家和敌人,你给他们增加了速度,不是吗?所以,这个速度肯定大于1(比如说,2)。因此,在某一时刻,会发生这样的情况,例如,body[i].x+30=99和player.x=100,而在下一时刻,在body[i]].x上加上"2"后,你会得到body[i][x+30=101和player.x=100。
代替这个条件(body[i].x+30==player.x),试着检查body[i]和player是否与以下条件重叠:
如果(body[i].x>player.x&body[i][i].x+30<=player.x){…}
我使用这种方法进行碰撞检测:
// **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
);
}
采用玛丽的实时代码从头开始编写JavaScript游戏-玛丽·罗斯·库克在2014年Front Trends上
- 使用JavaScript和HTML5画布进行冲突检测
- 检测阵列突变
- 如何在three.js中检测冲突
- Javascript/JQuery中的多DIV冲突检测
- three.js服务器端冲突检测错误
- 从数组绘制级别后的冲突检测
- 未检测到阵列中的图像
- 如何在 javascript 中检测两个图像之间的冲突
- 在 html canvas 元素上使用 javascript 进行冲突检测,而无需使用 jquery
- 关于不同屏幕尺寸的 Phonegap 游戏开发冲突检测
- 用于检测颜色冲突的 getImageData 不起作用
- 如何获取我的 x 和 y 值以检测 html5 画布中两个图像之间的冲突
- 如何检测与JS的冲突
- JavaScript中一帧的冲突检测
- Javascript 2阵列冲突检测
- 使用ajax检测阵列
- Javascript画布,通过数组进行冲突检测不起作用
- 在jquery中检测两个图像之间的冲突
- gameQuery冲突检测
- jQuery 拖动与冲突检测