Phaser 3 Sprite Keyboard.isDown表现异常

问题描述

我试图在Phaser 3中创建蛇游戏。arrow。(key).isDown的行为异常,我不知道为什么。如果您按下某个键,天气将向上,向下,向左或向右移动,如果您按下相反的方向,则不会改变方向,它只会不断移动。就像我按下时一样,即使按下后它也会持续下降。我已经尝试调试了几个小时。所有示例几乎都以相同的方式进行设置。

到目前为止,这是我的代码

class mainScene {
  preload() {
    this.load.image("fruit","images/fruit.png");
    this.load.image("snake","images/snake.png");
  }
  create() {
    this.score = 0;
    this.snake = this.physics.add.sprite(20,20,"snake");
    this.fruit = this.physics.add.sprite(
      Phaser.Math.Between(10,590),Phaser.Math.Between(10,"fruit"
    );
    this.scoreText = this.add.text(500,5,`score: ${this.score}`);
    this.arrow = this.input.keyboard.createCursorKeys();

    //debug
  }

  update() {
    if (this.physics.overlap(this.snake,this.fruit)) {
      this.hit();
    }
    this.snake.setVeLocity(0);
    if (this.arrow.right.isDown) {
      this.snake.setVeLocityX(50);
      if (this.snake.x > 600) {
        this.outOfBounds();
      }
    } else if (this.arrow.left.isDown) {
      this.snake.setVeLocityX(-50);
      if (this.snake.x < 0) {
        this.outOfBounds();
      }
    }

    if (this.arrow.down.isDown) {
      this.snake.setVeLocityY(50);
      if (this.snake.y > 600) {
        this.outOfBounds();
      }
    } else if (this.arrow.up.isDown) {
      this.snake.setVeLocityY(-50);
      if (this.snake.y < 0) {
        this.outOfBounds();
      }
    }
  }

  hit() {
    this.fruit.x = Phaser.Math.Between(10,590);
    this.fruit.y = Phaser.Math.Between(10,590);
    this.score += 1;
    this.scoreText.setText(`score: ${this.score}`);

    this.tweens.add({
      targets: this.snake,duration: 200,scaleX: 1.2,scaleY: 1.2,yoyo: true,});
  }

  outOfBounds() {
    this.score = 0;
    this.scoreText.setText(`score: ${this.score}`);
    this.gameOverText = this.add.text(
      100,250,"You went out of bounds.\nGame Over\nPress Space to continue.",{ fontSize: "24px" }
    );
    if (this.arrow.space.isDown) {
      this.gameOverText.destroy();
      this.scene.restart();
    }
  }
}

const config = {
  type: Phaser.CANVAS,width: 600,height: 600,backgroundColor: 0x000040,scene: mainScene,physics: {
    default: "arcade",debug: true,setBounds: { x: 0,y: 0,height: 600 },},parent: "game",};

new Phaser.Game(config);

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)