我遇到的问题是当npc和播放器在5个像素内时触发碰撞,然后npc的库存将显示在控制台中。问题是npc库存只会显示一次。
我想这样做,以便每当玩家在npc的5个像素内时,他们的库存就会显示出来。但是,当玩家在npc的5个像素内时,我也不希望碰撞不断触发,当他们第一次接近时只需要一次。
这是我的代码......
// collision for npc and player
function npc2Collision(){
for(var i = 0; i < 1; i++){
game.addEventListener('enterframe', function() {
//detects whether player sprite is within 5
//pixels of the npc sprite
if(player.within(npc2,5) && !npc2.isHit){
console.table(npcInvObject);
npc2.isHit = true;
}
});
}
}
npc2Collision();
答案 0 :(得分:1)
为了防止再次触发碰撞,您可以使用由支票设置的简单标志(及其反转):
function npc2Collision(){
for(var i = 0; i < 1; i++){
game.addEventListener('enterframe', function() {
//detects whether player sprite is within 5
//pixels of the npc sprite
if(player.within(npc2,5) && !npc2.isHit){
// split the checks so distance works well
if (!player.collided) {
console.table(npcInvObject);
npc2.isHit = true;
player.collided = true;
}
} else {
player.collided = false;
});
}
}
这将运行一次,在播放器上设置collided
标志,并且在玩家离开碰撞半径之前不会再次触发。