【发布时间】:2018-09-10 20:50:01
【问题描述】:
我正在学习 p5.js,但遇到了一个我还无法解决的问题。 所以我正在制作这个小游戏,你必须在其中射击敌人并躲避他们的技能。看起来是这样的:
右边是玩家,中间是子弹(用数组处理),左边是敌人(数组)。敌人和子弹都有自己的对象。 这是生成敌人和子弹的代码:
对于子弹
function shoot() {
x = p.x + 6.5;
y = p.y + 12.5;
bullets.push(new Bullet(x, y));
}
对于敌人:
function spawnEnemies() {
let x = 650;
let y = 30;
for (let i = 0; i < 14; i++) {
enemies.push(new Enemy(x, y));
y += 40
}
}
我想做的是在子弹到达目标时检测碰撞。我就是这样尝试的:
// check hit
for (let i = 0; i < bullets.length; i++){
for (let j = 0; j < enemies.length; j++){
let d = dist(bullets[i].x, bullets[i].y, enemies[j].x, enemies[j].y)
if (d < 1){
console.log('hit');
}
}
}
check hit 代码在 p5 的 draw 函数内部,因此它会连续执行。谁能帮帮我?
提前谢谢你!
【问题讨论】:
标签: javascript arrays collections detection p5.js