Making my character move right and left with arrow keys?

I am trying to move my spaceship right and left, but it gives me an error: Cannot read property ‘x’ of undefined, somehow my player variable is undefined and I can’t figure out why, can anyone tell me why and how can I fix it so that my ship moves? Here is my code:

var config = {
type: Phaser.AUTO,
width: 800,
height: 700,
physics: {
default: ‘arcade’,
arcade: {
gravity: {y: 500},
debug: false
},
},
scene: {
preload: preload,
create: create,
update: update
},
};

var game = new Phaser.Game(config);
var player;
var background;
var cursors;

function preload() {
this.load.image(‘background’, ‘./assets/star-background.jpg’);
this.load.image(‘player’, ‘./assets/spaceship.png’);
}

function create() {
background = this.add.image(400, 300, ‘background’);
player = this.add.sprite(400,600, ‘player’);
cursors = this.input.keyboard.createCursorKeys();
}

function update() {
if(cursors.right.isDown) {
player.position.x += 1;
}
else if(cursors.left.isDown) {
player.position.x -= 1;
}
}

Looking at the api I don’t see ‘Sprite.position’. Try setPosition( [x] [, y] [, z] [, w]) or setX().

You can also directly modify the x property of the player - player.x += 1. Game Objects’ positions aren’t stored as points in Phaser 3; each axis is a separate property.

Look at this tuto :


Is it helpful ?