I am making a little 2D game in p5.js and I have this Player class which... is a player(surprise :D) (Code is simplified)
class Player{
constructor(x,y){
this.x = x;
this.y = y;
}
}
And they Player is stored within a global array. The array also contains other player objects.
let globalPlayers = [new Player(0,0), new Player(0,0), new Player(0,0), new Player(0,0)]
To let all the players collide with each other, every player has to know every player.
Therefore every player has a method updating a copy of the global player array.
class Player{
constructor(x,y){
this.x = x;
this.y = y;
this.otherPlayer;
}
update(otherPlayers){
this.otherPlayer = otherPlayers;
}
}
I am constantly updating this particular array for every player in the array.
function draw() {
for(let i = 0; i < globalPlayers.length; i++){
globalPlayers[i].update(globalPlayers);
}
}
The problem is that the array within the player objects gets recursive. Because every player has an array with players. Each player of that array has an array with all players, and so on...
My question is: How can I improve the performance of this? Can I somehow prevent this from happening?
I am aware of the approach of just passing the globalPlayer array into methods of the Player when I really need them.( e.g. Player.checkCollision(globalPlayers) ). But I need the array constantly updated within the object itself.
Thanks in advance:)