我正在用Pixi JS制作一款游戏,如果我的猫与老鼠相撞,分数会增加+1。现在我的问题是,如果两个碰撞,分数不是增加1,而是每次碰撞增加30左右。即使所有的老鼠都从游戏中删除,分数被设置为零,它仍然会继续计数吗?
这是鼠标和猫碰撞时增加分数的代码,这不起作用
for (const mouse of this.mice) {
mouse.update(delta);
if (this.collision(this.cat, mouse)) {
// console.log("CAT ATTACK!!!!");
this.pixi.stage.removeChild(mouse);
//setTimeout(() => { this.interface.addScore(1); }, 5000);
this.interface.addScore(1);
//this.interface.score = Mouse.length;
}
}
这是我在ui中的代码。TS文件
export class ui extends PIXI.Container {
scoreField:PIXI.Text
score:number = 0
private game: Game;
constructor(game: Game){
super();
this.game = game;
const style = new PIXI.TextStyle({
fontFamily: 'ArcadeFont',
fontSize: 40,
fontWeight: 'bold',
fill: ['#ffffff']
})
this.scoreField = new PIXI.Text(`Score : 0`, style)
this.addChild(this.scoreField)
this.scoreField.x = 10
this.scoreField.y = 10
}
addScore(n:number) {
this.score += n
this.scoreField.text = `Score : ${this.score}`
}
}
最后,如果玩家输了,分数设为0,我从游戏中删除了所有的老鼠。我认为这可以确保分数不会重新开始计数,但即使没有老鼠和猫碰撞,它仍然在增加并高于零?
// when the Dog is the only survivor
if (
this.pixi.stage.children.filter((object) => object instanceof Dog)
.length === 1 &&
this.pixi.stage.children.filter((object) => object instanceof Cat)
.length === 0
) {
console.log("YOU LOSE");
let text = new PIXI.Text("You LOSE!!", { fill: ["#ffffff"] });
text.x = this.pixi.screen.width / 2;
text.y = this.pixi.screen.height / 2;
this.pixi.stage.addChild(text);
for (const dog of this.dogs) {
dog.update(delta);
this.pixi.stage.removeChild(dog);
for (const mouse of this.mice) {
this.pixi.stage.removeChild(mouse);
this.interface.score = 0;
}
this.interface.score = 0;
}
编辑:我修复了这个问题,只更新分数时,猫还在游戏
您可以在碰撞后用mouse.dead = true
标记鼠标。只有当mouse.dead
仍然设置为false时才计算分数。
for (const mouse of this.mice) {
if(mouse.dead === false) {
mouse.update(delta);
if (this.collision(this.cat, mouse)) {
mouse.dead = true;
this.pixi.stage.removeChild(mouse);
this.interface.addScore(1);
}
}
}
就像@domis86所说的那样,如果您不希望得到一个只包含不再相关的对象(不在舞台上的鼠标)的数组,那么您应该从数组中删除鼠标。棘手的部分是你在改变数组的同时仍然在循环,你可以通过向后循环来解决这个问题。
for (let i = this.mice.length-1; i>-1; i--) {
let mouse = this.mice[i];
mouse.update(delta);
if (this.collision(this.cat, mouse)) {
this.pixi.stage.removeChild(mouse);
this.interface.addScore(1);
this.mice.splice(i, 1)
}
}