I was wondering, is there any way to make the player a different object or scene that can interact with other scenes with this code structure? (for example: different stages)
This is an example of what I have for the character set-up inside the stage (if you want to have a closer look to the whole code, the GitHub repo is righ here)
init(){
this.charstateWalk = false;
this.charstateIdle = true;
this.charstateDead = false;
this.facingRight = true;
this.facingLeft = false;
}
create(){
this.cursors = this.input.keyboard.createCursorKeys(); //for the movement keys
this.platforms = this.physics.add.staticGroup(); //The platforms, should be behind the player
this.player = this.physics.add.sprite(100, 450, 'player'); //This creates the player itself
this.anims.create({
key: 'idle',
frames: [ { key: 'player', frame: 0 } ],
frameRate: 20
}); //for the idle animation (just 1 frame for now)
this.anims.create({
key: 'walk',
frames: this.anims.generateFrameNumbers('player', { start: 4, end: 7 }),
frameRate: 10,
repeat: -1
}); //for the walking animation
this.physics.add.collider(this.player, this.platforms, null, (player) => { return (this.player.body.velocity.y >= 0)}); //the platform collider, should be disabled when the character is going upwards (aka. jumping or stunned)
}
update(){
if(!this.charstateDead){
//This sets the sprite and the movement go ethier left or right
if(this.facingLeft == true){
this.player.setFlipX(true);
console.log("Fliping player anims to the Left")
}
else if(this.facingRight == true){
this.player.setFlipX(false);
console.log("Fliping player anims to the Right")
};
//Now we go with the movement handler
if(this.charstateWalk){
console.log("State: Walking");
if(this.facingLeft){
this.player.setVelocityX(-160);
console.log("Left, normal speed");
}
else if(this.facingRight){
this.player.setVelocityX(160);
console.log("Right, normal speed");
}
};
//Input handler, planned to be compatible with custom keybinding
if(this.cursors.left.isDown || this.cursors.right.isDown){
this.charstateWalk = true;
this.charstateIdle = false;
}
else{
this.charstateIdle = true;
this.charstateWalk = false;
};
// Animation handler, i should find a way to make something similar to "[characterKey]_walk" instead of "char1_walk" and "char2_walk" for optimization when i get to char2
if(this.Char1){
if (this.charstateWalk && this.player.body.onFloor())
{
this.player.anims.play('walk', true);
}
else if(this.charstateIdle){
this.player.anims.play('idle', true);
};
};
}
}