需要帮助合并2个位置数组和for循环
Need help merging 2 position arrays and for-loops
我正在制作一款游戏,我有两个数组,一个用于子弹变量,另一个用于敌人变量。它们都有独立的for循环,让目标发挥作用、移动、跟随、瞄准等。我现在只担心x和y值,它们存储在前两个数组值中(所以一个可能是敌人[0][0]是x值)。
有什么方法可以合并这两个,使它们相互作用吗?
for(var i = 0; i<enemies.length;i++){
enemies[i][0]+=blah blah blah;
enemies[i][1]+=blah blah blah;
}
for(var i = 0; i<bullets.length;i++){
bullets[i][0]+=blah blah blah;
bullets[i][1]+=blah blah blah;
}
基于评论这是我的游戏
https://i.stack.imgur.com/gqjlO.jpgfor(var i = 0; i < Math.max(enemies.length, bullets.length);i++){
if(i < enemies.length){
enemies[i][0]+=blah blah blah;
enemies[i][1]+=blah blah blah;
}
if(i < bullets.length){
bullets[i][0]+=blah blah blah;
bullets[i][1]+=blah blah blah;
}
}
基于注释的另一种方式:
for(var i = 0; i < bullets.length; i++){
//for each bullet
bullets[i][0]+=blah blah blah;
bullets[i][1]+=blah blah blah;
for(var j = 0; j < enemies.length;j++){
// each enemy
enemies[j][0]+=blah blah blah;
enemies[j][1]+=blah blah blah;
if(enemies[j].BBox.checkCollision(bullets[i])){
// they collide
}
}
}
如果你只有x和y坐标,它很难检查碰撞,你需要周围的边界框可能甚至子弹,我建议你使用OOP
如果你至少有偏移,碰撞检查可以这样做:
var bbox = {
'x': 0,
'y': 0,
'width': 100,
'height': 200
};
bbox.checkCollision = function(bullet){
return (bullet[0] > bbox.x && bullet[0] < bbox.x + bbox.width
&& bullet[1] > bbox.y && bullet[1] < bbox.y + bbox.height);
}
for(var i = 0; i < bullets.length; i++){
for(var j = 0; j < enemies.length;j++){
bbox.x = enemies[j][0];
bbox.y = enemies[j][1];
if(bbox.checkCollision(bullets[i])){
// bullets[i] collide with enemies[j]
}
}
}
相关文章:
- 在for循环中使用多维数组设置google.maps.Marker图标
- Javascript-用于展开数组的递归/for循环
- JavaScript-将for循环的多个结果推送到数组中
- 将值从for循环(在另一个for循环中)JavaScript中推送到数组
- 使用条件for循环更新数组-Javascript
- 使用for循环填充document.getelementbyid中的数组
- 将推入式数组与for一起使用..在..循环中
- For循环与数组不起作用
- 将数组与For循环进行比较
- 如何在 for 循环中访问 json 数组字段的名称
- 访问带有 for 循环中的计数器的数组
- 使用RegExp循环数组而不是for循环(Javascript)
- JavaScript:如何在 for 循环期间跳过数组中的当前项目?(继续?
- Javascript:数组和For循环基础知识
- 如何使用javascript中的for循环成对检索数组元素
- 如何使用for循环语句通过Ajax发送大数据数组
- 如何在JavaScript中正确地将对象从for循环推送到数组
- 对象作为关联数组:for循环
- Howler.js - 从数组/for循环中引用和触发文件
- 通过输入字段和php数组+ for循环声明和使用变量