Hi, I am creating an object in my main game scene, the object is a player and i want it to use the setVelocityX() function, but I have error saying cannot read properties of undefined (reading ‘setVelocityX’) so I am thinking maybe the object does not have physics and thats why the error. But i can not find how to give the player object physics. I do user this.physics.add.sprite to create the player, so i thought this would add physics.
class Game extends Phaser.Scene
{
constructor ()
{
super({"game"});
let aKey;
let dKey;
let inputKey;
}
create()
{
this.inputKey = this.input.keyboard.createCursorKeys();
this.add.image(400, 300, 'background');
player1 = this.createPlayer(200, 500, 'player1', player1);
player2 = this.createPlayer(600, 500, 'player2', player2);
};
createPlayer(x, y, key, player)
{
player = this.physics.add.sprite(x, y, key);
player.health = 100;
player.setCollideWorldBounds(true);
this.aKey = this.input.keyboard.addKey(Phaser.Input.Keyboard.KeyCodes.A);
this.dKey = this.input.keyboard.addKey(Phaser.Input.Keyboard.KeyCodes.D);
}
update()
{
if(this.aKey.isDown || this.dKey.isDown)
{
this.movePlayer();
}
}
movePlayer()
{
if(this.aKey.isDown)
{
player1.setVelocityX(-100);
}
else
if(this.aKey.isDown)
{
this.player1.setVelocityX(100);
}
}