简体   繁体   中英

Array[Object] as attribute in Object recursion problem(p5.js)?

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.( eg Player.checkCollision(globalPlayers) ). But I need the array constantly updated within the object itself.

Thanks in advance:)

By doing this: this.otherPlayer = otherPlayers you are constantly reassigning this.otherPlayer to otherPlayers as a reference (not a copy of values) so it's the same as if you do it only once.

Your implementation of Player.checkCollision(globalPlayers) could simply access globalPlayers itself:

Player.prototype.checkCollision = function() {
    const otherPlayers = globalPlayers.filter(x => x !== this);
    const radius = 10;
    for(otherPlayer of otherPlayers) {
        if(Math.sqrt((this.x - otherPlayer.x) ** 2 + (this.y - otherPlayer.y) ** 2) < radius) {
            console.log('Collision!');
        }
    }
}

Here 's an example. You don't have to keep on reassigning the arrays. Just pass the global array as a reference once to every player.

In the sketch, every player draws the length of its own this.otherPlayers array. When you press the mouse, a new player is added to the canvas and to the globalPlayers array. You can see that the other players also have access to the new player (the length of their this.otherPlayers array is increased by one).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM