Reputation: 347
i am trying to move the background when pressing the left button, i am using phaser and here is the code:
<!doctype html>
<html>
<head>
<meta charset="UTF-8" />
<title>hello phaser!</title>
<script src="phaser.min.js"></script>
</head>
<body>
<script type="text/javascript">
window.onload = function() {
var game = new Phaser.Game(800, 600, Phaser.AUTO, '', {
preload : preload,
create : create,
update : update
});
var score = 0;
var scoreText;
function preload() {
game.load.image('sky', 'sky.png');
}
function create() {
game.physics.startSystem(Phaser.Physics.ARCADE);
game.add.sprite(0, 0, 'sky');
}
function update() {
cursors = game.input.keyboard.createCursorKeys();
if (cursors.left.isDown) {
sky.body.velocity.x = -150;
}
}
};
</script>
</body>
</html>
when i run it nothing happen to the background and i do not know where is the problem
Upvotes: 0
Views: 2408
Reputation: 1
Just tried this out now.
var background;
function create() {
background = game.add.tileSprite(0, 0, this.game.width, this.game.height, 'sky');
background.fixedToCamera = true;
}
function update() {
if (cursors.left.isDown) {
background.tileposition.x = -150;
}
}
Although -150 may be too large :)
Upvotes: 0
Reputation: 25371
Your code has 3 errors at least.
you have no variant named "sky"
so, use
sky = game.add.sprite(0, 0, 'sky');
instead of
game.add.sprite(0, 0, 'sky');
create cursors should be in create function , not update function.
cursors = game.input.keyboard.createCursorKeys();
you should enable physics for sprite manually. by default, sprite has no physics.
game.physics.enable(sky, Phaser.Physics.ARCADE);
runable js code likes this:
var game = new Phaser.Game(800, 600, Phaser.AUTO, '', {
preload : preload,
create : create,
update : update
});
var sky;
var cursors;
function preload() {
game.load.image('sky', 'sky.png');
}
function create() {
game.physics.startSystem(Phaser.Physics.ARCADE);
sky = game.add.sprite(0, 0, 'sky');
game.physics.enable(sky, Phaser.Physics.ARCADE);
cursors = game.input.keyboard.createCursorKeys();
}
function update() {
if (cursors.left.isDown) {
sky.body.velocity.x = -150;
} else {
sky.body.velocity.x = 0;
}
}
Upvotes: 2
Reputation: 3375
Glad you've found the answer already, but just to add that this line:
cursors = game.input.keyboard.createCursorKeys();
should not be in the update function. It should be set just once in create.
Upvotes: 2