无法在Phaser.js中动画Sprite
我正在尝试使用Sprite工作表来移动箭头键的字符,但似乎没有工作。如果我将背景设置为大于500,500,屏幕会与角色一起移动,但我希望角色能够自由移动,而不会随背景移动。无法在Phaser.js中动画Sprite
我可以在我的代码中更改哪些字符,以便使用箭头键移动字符?并使动画实际工作?
window.onload = function() {
var game = new Phaser.Game(500, 500, Phaser.AUTO, 'phaser-example',{ preload: preload, create: create });
function preload() {
game.stage.backgroundColor = '#fc6b84';
game.load.spritesheet('player', 'reddude.png', 64, 64);
}
function create() {
// This simply creates a sprite using the player image we loaded above and positions it at 200 x 200
var test = game.add.sprite(250, 250, 'player');
player.animations.add('walk');
player.anchor.setTo(0.5, 1);
game.physics.arcade.enable(player);
player.body.collideWorldBounds = true;
addItems();
addPlatforms();
cursors = game.input.keyboard.createCurosrKeys();
//game set up
}
function update() {
game.physics.arcade.collide(player, platforms);
game.physics.arcade.overlap(player, items, itemHandler);
game.physics.arcade.overlap(player, badges, badgeHandler);
player.body.velocity.x = 0;
// is the left cursor key presssed?
if (cursors.left.isDown) {
player.animations.play('walk', 10, true);
player.body.velocity.x = -50
player.scale.x = - 1
}
// is the right cursor key pressed?
else if (cursors.right.isDown) {
player.animations.play('walk', 10, true);
player.body.velocity.x = 50
player.scale.x = 1
}
else if (cursors.up.isDown) {
player.animations.play('walk', 10, true);
player.body.velocity.y = 50
player.scale.y = 1
}
else if (cursors.down.isDown) {
player.animations.play('walk', 10, true);
player.body.velocity.y = -50
player.scale.y = -1
}
// player doesn't move
else {
player.animations.stop();
}
}
}
添加名为test
的精灵变量,但将动画添加到名为player
的变量。这可能是你犯的一个错误,我的意思是var player
定义在哪里?
至于不同的动画工作,你必须分别添加每个动画到你的精灵变量。您必须指出哪些帧用于“走左”动画,哪些帧用于“走起来”动画等,并创建单独的动画。类似这样的:
// define variable globally, outside "create()", so then "update" can also use the variable
var playersprite;
// create a sprite in the "create()" function
// note: playersprite is the variable name and 'player' is the spritesheet name string
playersprite = game.add.sprite(250, 250, 'player');
// add animations to sprite
playersprite.animations.add('walk_down', [0,1,2,3]);
playersprite.animations.add('walk_left', [4,5,6,7]);
playersprite.animations.add('walk_right', [8,9,10,11]);
playersprite.animations.add('walk_up', [12,13,14,15]);
然后根据播放器的移动方向,播放不同的动画。
// when LEFT cursor key presssed
if (cursors.left.isDown) {
playersprite.animations.play('walk_left', 10, true);
// etc.
你可以让相机跟随您的播放器。第一箱箱玩家精灵然后添加以下行:
game.camera.follow(player);
你可以在这个链接找到你需要什么。 https://phaser.io/examples/v2/camera/basic-follow
此外,你不应该声明你的变量为“var player”而不是“var test”里面的创建函数吗?
谢谢!那是我需要的!但现在我似乎无法弄清楚如何在移动角色时使动画起作用,当我按下某个按键时,动画会播放整个精灵表而不是一行,但动画也不会停止放开钥匙。我希望能够使动画在不同的行中工作,例如,如果我按下向下箭头,我希望第一行只播放,当我放开时,我希望它停止。 – hannacreed
@hannacreed我不知道我是否理解你,这将是很好,你发布第二个问题的另一个问题,并张贴代码只与角色动画,然后告诉我们什么不按预期工作。 –
您的代码根本不起作用。从这个开始(https://jsfiddle.net/archierocks183/zygz2ksm/17/),并让它进入工作阶段,以获得更好的帮助 –