Phaser笔记-scene中的preload、create、update、player、键盘控制

2023-05-16

一般phaser最简单的配置文件如下:

let config = {
        type: Phaser.AUTO,
        width: 800,
        height:600,
        scene: {
            preload: preload,
            create: create,
            update: update
        },
        physics:{
            default: 'arcade',
            arcade: {
                gravity: { y: 300},
                debug: false
            }
        }
    };

其中scene有3个函数:preload、create、update

preload:是在create函数前调用的,一般用于资源的加载;

create:preload完成后,就会调用到这函数,这个函数一般用于构造界面,关联玩家键盘,游戏大部分逻辑事件等等等;

update:会按周期进行调用,一般用于键盘控制玩家,玩家坐标更新等。

下面是player键盘控制,首先定义变量:

let player;

create函数中奖player构造成精灵,并且设置好回弹参数以将碰撞属性设置为true:

player = this.physics.add.sprite(100, 450, 'dude');
player.setBounce(0.2);
player.setCollideWorldBounds(true);

如果给出的精灵是这样的:

那么还需要创建动画,方便后边的键盘操作,上面的精灵是个横版的图,左边4幅是左,中间那一幅是停止的,右边4幅是右走。

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

 比如横版游戏中有个platforms,玩家可以站在平台上:

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

在平台上有些加分道具(如stars),当玩家捡到(重叠)到加分道具会执行对应的回调函数:

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

其中stars是变量,collectStar是回调函数。

同样平台上还会有一些敌人,如果玩家接触到这些敌人也会触发对应的回调函数:

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

其中hitBomb就是回调函数。

关于键盘首先定义cursor变量:

let cursors;

在create函数中创建光标:

cursors = this.input.keyboard.createCursorKeys();

在update函数中通过按下不同的键盘干不同的事情:

function update(){

    if(cursors.left.isDown){
    }
    else if(cursors.right.isDown){
    }
    else{
    }

    if(cursors.up.isDown && player.body.touching.down) {
    }

}

分别是左键被按下,右键被按下,跳起一次。

如将玩家(精灵)在不同操作下,设置不同的X,Y轴坐标,以及播放不同的动画。

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', true);
    }

    if(cursors.up.isDown && player.body.touching.down) {

            player.setVelocityY(-330);
    }
}

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Phaser笔记-scene中的preload、create、update、player、键盘控制 的相关文章

  • 银河麒麟PyCharm中文设置

    银河麒麟自带的PyCharm xff08 社区版 xff09 可以设置成中文 xff0c 直接上图 在File Settings 在Plugins搜索 Chinese xff0c 下载安装后 xff0c 重启PyCharm xff0c 变成

随机推荐