Sprite带有箭头键的表格动画
问题描述:
我似乎无法弄清楚如何在移动字符时动画工作,当我按下某个键时,动画将播放整个精灵表格而不是一行,动画当我放开钥匙时也不会停下来。我希望能够使动画在不同的行中工作,例如,如果我按下向下箭头,我希望第一行只播放,当我放开时,我希望它停止。Sprite带有箭头键的表格动画
当我按下不同的按键时,请帮助我使用此代码来为不同的行添加动画角色,并且当我释放一个按键时能够停止动画。
如您所见,图像的第一行用于按下向下键,第二行用于左键,第三行用于右键,第四行用于向上键。
请随身携带,因为我是编码新手。
我使用Photon Storm的Phaser javascript框架。
的JavaScript,game.js:
var game = new Phaser.Game(800, 600, Phaser.CANVAS, 'phaser-example', {
preload: preload, create: create, update: update, render: render });
function preload() {
game.stage.backgroundColor = '#ff6288';
game.load.spritesheet('player','reddude.png', 64, 64);
}
var player;
var cursors;
function create() {
game.add.tileSprite(0, 0, 1920, 1920, 'background');
game.world.setBounds(0, 0, 1920, 1920);
game.physics.startSystem(Phaser.Physics.P2JS);
player = game.add.sprite(game.world.centerX, game.world.centerY,
'player');
game.physics.p2.enable(player);
player.animations.add('walk');
player.anchor.setTo(0.5, 1);
cursors = game.input.keyboard.createCursorKeys();
game.camera.follow(player);
}
function update() {
player.body.setZeroVelocity();
if (cursors.up.isDown)
{
player.animations.play('walk', 10, true);
player.body.moveUp(100)
}
else if (cursors.down.isDown)
{
player.animations.play('walk', 10, true);
player.body.moveDown(100);
}
if (cursors.left.isDown)
{
player.animations.play('walk', 10, true);
player.body.velocity.x = -100;
}
else if (cursors.right.isDown)
{
player.animations.play('walk', 10, true);
player.body.moveRight(100);
}
}
function render() {
game.debug.cameraInfo(game.camera, 32, 32);
game.debug.spriteCoords(player, 32, 500);
}
HTML:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Simple Canvas Game</title>
<style>
html {
background: black
}
canvas {
margin: auto;
}
</style>
</head>
<body>
<script src="phaser.js"></script>
<script src="game.js"></script>
</body>
</html>
答
首先,你需要在create()
定义多个动画。每个方向一个。
https://phaser.io/docs/2.6.2/Phaser.AnimationManager.html#add
player.animations.add('down', [0,1,2,3]);
player.animations.add('left', [4,5,6,7]);
player.animations.add('right', [8,9,10,11]);
player.animations.add('up', [12,13,14,15]);
然后你需要在update()
播放特定动画每个方向:
https://phaser.io/docs/2.6.2/Phaser.AnimationManager.html#play
https://phaser.io/docs/2.6.2/Phaser.AnimationManager.html#stop
if (cursors.up.isDown){
player.animations.play('up', 10, false);
player.body.moveUp(100);
} else if (cursors.down.isDown) {
player.animations.play('down', 10, false);
player.body.moveDown(100);
} else if (cursors.left.isDown) {
player.animations.play('left', 10, false);
player.body.velocity.x = -100;
} else if (cursors.right.isDown) {
player.animations.play('right', 10, false);
player.body.moveRight(100);
} else {
player.animations.stop(null, true);
}
太感谢你了,我觉得愚蠢,我在你回答之前像这样重新编写了我的代码,但我忘了框架不是以1开始,而是以0开始。 – hannacreed