【问题标题】:advice with my javascript collision detection关于我的 javascript 碰撞检测的建议
【发布时间】:2017-12-12 23:20:18
【问题描述】:

我正在尝试制作一款让人想起旧 Galaga 游戏的自上而下的射击游戏。 除了尝试检查玩家发射的子弹与敌方飞船之间的碰撞之外,我已经让玩家、敌人和射弹移动并正常工作。

子弹和敌人都是使用构造函数创建的,然后放置在一个数组中以跟踪它们。

//due to the number of enemies on screen they'll be held in an array
var enemies = [];
    for(e = 0; e < enemies; e++) {
        enemies[e] = [];
        enemies[e] = {x:0,y:0};
}

//class constructor to create enemies
class enemy {
    constructor(x,y) {
        this.enemyX = x;
        this.enemyY = y;
        this.enemyWidth = 32;
        this.enemyHeight = 32;
    }
}

//variable array for the bullets
var playerBullets = [];
    for(i = 0; i < playerBullets; i++) {
    playerBullets[i] = { x: 0, y: 0 };
}

//class constructor to create the bullets
class bullet {
    constructor(x,y){
        this.bulletX = x;
        this.bulletY = y;
        this.bulletWidth = 5;
        this.bulletHeight = 5;
    }
}

我尝试制作一个碰撞检测器功能,该功能首先通过子弹阵列,然后是敌人阵列并检查重叠边界并在发现碰撞时发出警报,但我遇到了麻烦它。如果有人可以提供帮助,我将不胜感激。

//code for detecting collisions from the bullets
function collisionDetection() {
    for(i = 0; i < playerBullets.length; i++) {
        for(e = 0; e < enemies.length; e++) {   
            if (playerBullets[i].x < enemies.x + enemy.width  && 
playerBullets[i].x + bullet.width  > enemies.x &&
            playerBullets[i].y < enemies.y + enemy.height && 
playerBullets[i].y + bullet.height > enemies.y){
                alert("HIT");
            }
        }   
    }
}

【问题讨论】:

  • @Peter 当代码处于工作状态时,可以将其发布到那里。但在那之前,OP 输入了“我遇到了麻烦。”,因此它将是off-topic
  • sorry my bad,如果子弹和敌人都是圆形的,你只需要用勾股定理计算中点距离,如果C小于2个圆形无线电,那就是命中。
  • 不,子弹和敌人都是方形的,目前我很确定这是“如果”语句是错误的,但对于我的生活,我无法弄清楚如何
  • @Dodge 如果x y坐标是敌人/子弹的中点,则需要将高宽除以2

标签: javascript collision-detection


【解决方案1】:

你错过了敌人的索引:enemies[e],并且敌人有enemyXenemyYenemyWidthenemyHeight属性,而bullets有:bulletXbulletYbulletWidth@987654 @

function collisionDetection() {
    for(i = 0; i < playerBullets.length; i++) {
        for(e = 0; e < enemies.length; e++) {   
            if (playerBullets[i].bulletX < enemies[e].enemyX + enemies[e].enemyWidth && 
playerBullets[i].bulletX + playerBullets[i].bulletWidth > enemies[e].enemyX &&
            playerBullets[i].bulletY < enemies[e].enemyY + enemies[e].enemyHeight && 
playerBullets[i].bulletY + playerBullets[i].bulletHeight > enemies[e].enemyY){
                alert("HIT");
            }
        }   
    }
}

【讨论】:

    猜你喜欢
    • 2021-02-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-18
    相关资源
    最近更新 更多