I am wanting to use a function to create players, so i have created a function, but I also want to be able to deal damage to the players (there will be multiple players) and I can not figure out how to do this. I have managed to spawn different players using
function Spawn_players(x,y,texture)
{
const player = this.physics.add.sprite(x,y,texture)
this.Player_health = 100;
}
And all this is working fine, but I just can not figure out how i would give the players damage when they are hit by an enemy. Do i have a new function for this?
If you want to have multiple players this.Player_health won’t work, because you could only save a single HP in your game, instead of multiple.
You could instead create a list (an array) of players and save its health within the sprite object.
You can then create a function Deal_damage to decrease this health value, by array index, whenever you want.
create ()
{
this.players = []
this.Spawn_players(100,100, 'playerTexOne')
// If you want to do something with playerOne you can call `this.players[0]`
}
function Spawn_players(x,y,texture)
{
const player = this.physics.add.sprite(x,y,texture)
player.health = 100
this.players.push(player)
}
/**
* For playerOne `playerNo` must be 0, for playerTwo 1, ect...
*/
function Deal_damage(playerNo, damage)
{
this.players[playerNo].health -= damage
}