如何在Phaser中制作具有固定移动距离的精灵

时间:2019-01-06 21:15:06

标签: phaser-framework

我有一个基于街机游戏的基于网格的自上而下游戏,我希望我的玩家在网格位置之间精确移动。但是我该怎么办?

我现在使用速度在按下键盘上移动播放器,然后在update上将速度重置为0,这样就没有惯性了。

 function update(){

    this.player.body.velocity.x = 0
    this.player.body.velocity.y = 0

    if(this.keyIsLeft){
      this.player.body.velocity.x -= 200
    }
    else if(this.keyIsRight){
      this.player.body.velocity.x += 200
    }
    else if(this.keyIsUp){
      this.player.body.velocity.y -= 200
    }
    else if(this.keyIsDown){
      this.player.body.velocity.y += 200
    }

但是如何让玩家一次只能移动一个正方形(或半个正方形)?

此Lolo游戏中显示了理想的动作,在任何给定时间,玩家都处于网格或半网格空间:https://www.youtube.com/watch?v=QQKScIJYUxU&t=5m30s

我不能只设置x和y位置或使用补间,因为我需要保持街机物理,并且这些调整会干扰它们。

1 个答案:

答案 0 :(得分:0)

更新: 这是我为解决这种情况而更新的答案。 我基于Phaser提供的示例实现了此方法。 进行此固定移动的关键部分是在移动项目时禁用键盘输入。

比方说,如果您按下left键,那么player就会向左移动。 player开始移动时,将变量notMoving设置为false,这会通知update函数不接受任何光标输入。超时后,假设为1000毫秒,您可以将变量notMoving设置为true。然后update函数将继续获取光标输入。

以下是示例代码段:

function create ()
{
    cursors = this.input.keyboard.createCursorKeys();
    player = this.physics.add.image(400, 300, 'block');
    player.setCollideWorldBounds(true);
    player.setData('notMoving', true);

}

function setfixedMovement(velocity, direction) {
    if (direction === 'up') {
        player.setVelocityY(-velocity);
    } else if (direction === 'down') {
        player.setVelocityY(velocity);
    } else if (direction === 'left') {
        player.setVelocityX(-velocity);
    } else {
        player.setVelocityX(velocity);
    }
    player.setData('notMoving', false);
    setTimeout(() => {
        player.setData('notMoving', true);
    }, 1000);
}

function update () {
    if (player.getData('notMoving')) {
        player.setVelocity(0);
        if (cursors.left.isDown) {   
            setfixedMovement(300, 'left');
        } else if (cursors.right.isDown) {
            setfixedMovement(300, 'right');
        }

        if (cursors.up.isDown) {
            setfixedMovement(300, 'up');
        } else if (cursors.down.isDown) {
            setfixedMovement(300, 'down');
        }
    }
}

我将移相器示例链接放在上一个答案中。如果您编辑示例并将示例代码的一部分替换为我上面提供的代码段,则可以看到它按预期工作。

上一个答案

我认为此移相器示例完全可以完成您想做的事情

简而言之, 在每次更新中,将速度设置为0, 然后检测检查光标键状态并相应地设置速度 以下代码是从Official Phaser 3 Example复制的

function update ()
    { player.setVelocity(0);

    if (cursors.left.isDown)
    {
        player.setVelocityX(-300);
    }
    else if (cursors.right.isDown)
    {
        player.setVelocityX(300);
    }

    if (cursors.up.isDown)
    {
        player.setVelocityY(-300);
    }
    else if (cursors.down.isDown)
    {
        player.setVelocityY(300);
    }
}

这里是示例的链接 https://labs.phaser.io/view.html?src=src\input\keyboard\cursor%20keys.js

相关问题