【问题标题】:How to restart a game in Phaser 3?如何在 Phaser 3 中重新开始游戏?
【发布时间】:2020-09-28 14:16:09
【问题描述】:

我是 Phaser 3 和游戏开发的新手,所以我遇到了问题。我正在尝试重新启动游戏场景,但是当我运行它时出现“未捕获的类型错误:this.scene.restart 不是函数”的错误

var playbtn = this.add.dom(390, 600).createFromCache('play-btn');

    playbtn.setPerspective(600);

    playbtn.addListener('click');

    playbtn.on('click', function (event) {
        this.scene.restart();
    });

这是我的全部代码

<!doctype html> 
<html lang="en"> 
<head> 
    <meta charset="UTF-8" />
    <title>Making your first Phaser 3 Game - Part 10</title>
    <script src="https://cdn.jsdelivr.net/npm/phaser@3.24.1/dist/phaser.js"></script>
    <style type="text/css">
        body {
            margin: 0;
        }
    </style>
</head>
<body>

<script type="text/javascript">

var config = {
    type: Phaser.AUTO,
    width: 800,
    height: 600,
    parent: 'phaser-example',
    physics: {
        default: 'arcade',
        arcade: {
            gravity: { y: 300 },
            debug: false
        }
    },
    dom: {
        createContainer: true
    },
    scene: {
        preload: preload,
        create: create,
        update: update,
        hitbomb: hitBomb
    }
};
var game = new Phaser.Game(config);


var player;
var stars;
var bombs;
var platforms;
var cursors;
var score = 0;
var gameOver = false;
var scoreText;

var level_state;
var level = 1;

var de_star = 0;
var element;
var playbtn;


function preload ()
{
    this.load.image('sky', 'assets/sky.png');
    this.load.image('ground', 'assets/platform.png');
    this.load.image('star', 'assets/bomb.png');
    this.load.image('bomb', 'assets/star.png');
    this.load.spritesheet('dude', 'assets/dude.png', { frameWidth: 32, frameHeight: 48 });
    this.load.html('play-btn', 'assets/play.html');
    this.load.html('nameform', 'assets/loginform.html');
   
}

function create ()
{

    //  A simple background for our game
    this.add.image(400, 300, 'sky');

    //  The platforms group contains the ground and the 2 ledges we can jump on
    platforms = this.physics.add.staticGroup();

    //  Here we create the ground.
    //  Scale it to fit the width of the game (the original sprite is 400x32 in size)
    platforms.create(400, 568, 'ground').setScale(2).refreshBody();

    //  Now let's create some ledges
    platforms.create(600, 400, 'ground');
    platforms.create(50, 250, 'ground');
    platforms.create(750, 220, 'ground');

    // The player and its settings
    player = this.physics.add.sprite(100, 450, 'dude');

    //  Player physics properties. Give the little guy a slight bounce.
    player.setBounce(0.2);
    player.setCollideWorldBounds(true);

    //  Our player animations, turning, walking left and walking right.
    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
    });

    //  Input Events
    cursors = this.input.keyboard.createCursorKeys();

    //  Some stars to collect, 12 in total, evenly spaced 70 pixels apart along the x axis
    stars = this.physics.add.group({
        key: 'star',
        repeat: 1,
        setXY: { x: 12, y: 0, stepX: 70 }
    });

    stars.children.iterate(function (child) {
        //  Give each star a slightly different bounce
        child.setBounceY(Phaser.Math.FloatBetween(0.4, 0.8));

    });

    bombs = this.physics.add.group();

    //  The score
    scoreText = this.add.text(16, 16, 'score: 0', { fontSize: '32px', fill: '#000' });
    level_state = this.add.text(16, 50, 'Level: 1', { fontSize: '32px', fill: '#000' });


    //  Collide the player and the stars with the platforms
    this.physics.add.collider(player, platforms);
    this.physics.add.collider(stars, platforms);
    this.physics.add.collider(bombs, platforms);

    //  Checks to see if the player overlaps with any of the stars, if he does call the collectStar function
    this.physics.add.overlap(player, stars, collectStar, null, this);

    this.physics.add.collider(player, bombs, hitBomb, null, this);
}

function update ()
{
    if (gameOver)
    {
        return;
    }

    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);
    }
}

function collectStar (player, star)
{
    star.disableBody(true, true);

    //  Add and update the score
    score += 10;
    scoreText.setText('Score: ' + score);
    if (de_star==12)
    {
        gameOver = True;
    }
    else if (stars.countActive(true) === 0)
    {

        de_star+=1;
        stars = this.physics.add.group({
        key: 'star',
        repeat: 11-de_star,
        setXY: { x: 12, y: 0, stepX: 70 }
        });

        this.physics.add.collider(stars, platforms);

        stars.children.iterate(function (child) {

        //  Give each star a slightly different bounce
        child.setBounceY(Phaser.Math.FloatBetween(0.4, 0.8));

        });

        //  A new batch of stars to collect
        stars.children.iterate(function (child) {

            child.enableBody(true, child.x, 0, true, true);

        });

        this.physics.add.overlap(player, stars, collectStar, null, this);

        var x = (player.x < 400) ? Phaser.Math.Between(400, 800) : Phaser.Math.Between(0, 400);

        level += 1;

        var bomb = bombs.create(x, 16, 'bomb');
        bomb.setBounce(1);
        bomb.setCollideWorldBounds(true);
        bomb.setVelocity(Phaser.Math.Between(-200, 200), 20);
        bomb.allowGravity = false;

    }
    level_state.setText('Level: '+level);
}

function hitBomb (player, bomb)
{
    this.physics.pause();

    player.setTint(0xff0000);

    player.anims.play('turn');

    gameOver = true;

    var playbtn = this.add.dom(390, 600).createFromCache('play-btn');

    playbtn.setPerspective(600);

    playbtn.addListener('click');

    playbtn.on('click', function (event) {
        this.scene.restart();
    });
    
    this.tweens.add({
        targets: playbtn,
        y: 300,
        duration: 3000,
        ease: 'Power3'
    });
}


</script>

</body>
</html>

当角色击中炸弹时,会弹出“重玩”按钮,如果玩家点击该按钮,游戏将重新开始。这些是我的目标... 我正在从事的项目是一个教程示例,但任何建议或解决方案都会对我有很大帮助。谢谢

【问题讨论】:

    标签: javascript phaser-framework


    【解决方案1】:

    正如@Thomas 已经指出的,这是this 的问题。

    你可以用粗箭头

        playbtn.on('click', (event) => {
            this.scene.restart();
        });
    

    或者您可以将上下文传递给“on”函数,我认为这是查看您的代码的“游戏”。

        playbtn.on('click', function (event) {
            this.scene.restart();
        }, game);
    

    这里是 Phaser 的 on 文档中的一个 sn-p

        /**
         * Add a listener for a given event.
         * @param event The event name.
         * @param fn The listener function.
         * @param context The context to invoke the listener with. Default this.
         */
        on(event: string | symbol, fn: Function, context?: any): this;
    

    【讨论】:

      【解决方案2】:

      我对 Phaser 不是很熟悉,但可能事件处理程序中的this 指的是按钮。使用粗箭头将处理函数绑定到周围作用域的this

          playbtn.on('click', (event) => {
              this.scene.restart();
          });
      

      【讨论】:

      • 非常感谢,它成功了。但是,我的游戏重新启动后没有收到任何输入作为事件,这意味着角色只是站着僵硬,我根本无法控制他。我不知道我是否必须删除 playbtn 的“点击”事件或类似的东西。希望你能给我更多的解决方案,Phaser 对我来说是全新的。
      • @deone 你应该为此打开一个新问题,如果你还没有弄清楚的话。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-03-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-04-02
      相关资源
      最近更新 更多