Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice
  2. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

Should I check the enemy distance from player in update?

Discussion in 'Scripting' started by Spaguetti, Mar 9, 2019.

  1. Spaguetti

    Spaguetti

    Joined:
    Oct 20, 2018
    Posts:
    4
    I am making a enemy that chases the player when he gets within a radius, but my game will have lots of enemies, so I'm thinking if checking the distance in update for so much characters would be really the best practice. Any advices?
     
  2. Stevens-R-Miller

    Stevens-R-Miller

    Joined:
    Oct 20, 2017
    Posts:
    676
    There are many ways to deal with this. First, ignore the problem until you see it is slowing you down. That may never happen. If it does, one trick you can try is to partition your world into spaces and only check for enemies in the same space as your player, and for enemies that are in spaces adjacent to the space your player is in. Make your spaces just big enough to include the radius you care about. Whenever your player moves from one space to another, update the enemies that are no longer in spaces that need to check so they stop checking, and update enemies that are in spaces that must now start checking. You will have to update each enemy individually if they move on their own, whenever one of them changes spaces.

    Craig Reynolds addressed this problem in his paper, "Flock, Herds, and Schools: A Distributed Behavioral Model," in 1987. Still good stuff today.
     
    Spaguetti likes this.