开发者问题收集

玩家不动 Phaser3 学习

2022-09-29
117

我正在通过查看phaser3的第6页进行学习,但是即使在网站上执行相同的操作也会出错。我可以跳转,但是左右控制器都出错了。这是为什么呢?

我应该如何指定类型?我需要你们的帮助,伙计们!

Uncaught TypeError:无法读取未定义的属性(读取'duration')

function App() {
  // ..
  let platforms;
  let player: any;
  let cursors: any;

  function preload(this:any){
    // ..
    this.load.image('dude', 'src/assets/dude.png', {frameWidth: 32, frameHeight: 48});
  }

  function create(this:any){
    this.add.image(400,300,'sky');
    this.add.image(0,0, 'star').setOrigin(0, 0);

    platforms = this.physics.add.staticGroup();;
    platforms.create(400,568, 'plane').setScale(2).refreshBody();
    // ..

    player = this.physics.add.sprite(100, 450, 'dude')

    player.setBounce(0.2);
    player.setCollideWorldBounds(true);

    this.anims.create({
      key: 'left',
      frames:this.anims.generateFrameNumbers('dude', {start:0, end:3}),
      frameRate: 10,
      repeat: -1
    });

    this.anims.create({
      key: 'turn',
      frames:[{key: 'dude', frame:4}],
      frameRate: 20
    });

    this.anims.create({
      key: 'right',
      frames:this.anims.generateFrameNumbers('dude', {start:5, end:8}),
      frameRate: 10,
      repeat: -1
    });

    this.physics.add.collider(player, platforms);
    
    cursors = this.input.keyboard.createCursorKeys();
    console.log(cursors)
  }

  function update(){
    if(cursors.left.isDown) {
      player.setVelocityX(-160);
      player.anims.play('left', true);
    } else if(cursors.right.isDown){
      player.setVelocityX(160);
      player.anims.play('right', true);
    } else {
      player.setVelocityX(0);
      player.anims.play('turn');
    }
    if(cursors.up.isDown && player.body.touching.down){
      player.setVelocityY(-330);
    }
  }

// ..
2个回答

由于代码似乎是正确的,因此问题 可能 是由于图像的 frameWidth 和/或 frameHeight 可能太大 (意思是:大于实际图像大小, 即使 1px 差异 也足以导致错误) 。这可能会产生类似这样的错误:

Uncaught TypeError: Cannot read properties of undefined (reading 'duration') ...

但它仍然会显示图像。只需检查图像的尺寸 (在 preload 函数中加载的图像) 是否是 frameWidthframeHeight 的倍数。

Based from this older answer ( https://stackoverflow.com/a/72067212/1679286 )

winner_joiner
2022-09-29

这看起来像是一个简单的拼写错误,我很惊讶 TypeScript 没有发现它:

function preload(this:any){
  // ..
  this.load.image('dude', 'src/assets/dude.png', {frameWidth: 32, frameHeight: 48});
}

您正在将其加载为 image ,但您应该将其加载为 spritesheet

this.load.spritesheet('dude', 'dude.png',
    { frameWidth: 32, frameHeight: 48 }
);
James Skemp
2022-10-15