开发者问题收集

setCollideWorldBounds(true) 不是函数,使用 Phaser 3

2020-06-28
1483

使用 Phaser 3,我尝试使用 setCollideWorldBounds ,但它总是告诉我这不是一个函数。我已经将物理添加到游戏中,但它仍然不起作用。

window.onload = function() {
config = {
    type: Phaser.AUTO,
    width: 800,
    height: 500,
    scene: [Scene, Scene2],
    physics: {
        default: 'arcade',
        arcade: {
          gravity: { y: 200 },
          enableBody: true,
        }
    }
}
var game = new Phaser.Game(config);
}

create() {
    this.background = this.add.tileSprite(0,0,800,500,"space");
    this.background.setOrigin(0,0);
    this.spaceship = this.add.sprite(0,Phaser.Math.Between(1,width),"spaceship");
    this.player_spaceship = this.add.sprite(400,250,"player_spaceship");
    this.scoreText = this.add.text(16,16, 'score: 0', { fontSize: '32px', fill: 'red' });
    this.keys = this.input.keyboard.addKeys("W,A,S,D");
    this.anims.create ({
        key: "player_spaceship", //name of the animation
        frames: this.anims.generateFrameNumbers("player_spaceship"), //takes the spritesheet
        frameRate:20, // frames per seconds
        repeat: -1 // repeat infinite
    });
    this.player_spaceship.setCollideWorldBounds(true);
    this.spaceship.play("player_spaceship");
    this.player_spaceship.play("player_spaceship");
}
1个回答

setCollideWorldBounds 是 Arcade Body 和(为方便起见)Arcade Sprite 类上的一种方法。不幸的是,它不是 sprite 类本身的方法,而您的代码正在使用 sprite 类。

1. 原版 sprite

可以 使用“原版”sprite,然后为其添加物理效果:

// Assumes the `create` method was snipped from a Scene class
this.player_spaceship = this.add.sprite(400, 250, "player_spaceship");
this.physics.world.enable(this.player_spaceship);
this.player_spaceship.body.setCollideWorldBounds(true);
// nit: don't add me to any physics groups below this line, or I'll forget you want me to collide with the world bounds! Weird but true.

2. Arcade sprite

或者,您也可以只使用物理类和工厂来隐藏一点复杂性:

this.player_spaceship = this.physics.add.sprite(400, 250, "player_spaceship");
this.player_spaceship.setCollideWorldBounds(true);
// You *could* use the body here instead if you wanted! But since you have the convenience method, might as well use it.

哪种方法更好?

嗯。可能是方法 2。取决于您的游戏。

Andrew Cunningham
2020-12-01