Finding the nearest spawn point

Rather than randomly choosing a spawn point or waypoint in some cases, we will want to choose the closest point to the current position of the player or camera. This recipe builds on the previous one to move the player's red cube to the closest tagged Respawn object each time the Fire key is clicked.

Getting ready

This recipe builds upon the previous one, so make a copy of that Unity project then follow the steps of this recipe.

How to do it...

To find the nearest spawn point, perform the following steps:

  1. Remove the SpawnBall scripted component from the Main Camera.
  2. Enable the Mesh Rendered components of your two spawn point capsules (so you can see these white capsules on the terrain).
  3. Add the following C# script class to Cube-player:
    // file: NearestSpawnpoint
    using UnityEngine;
    using System.Collections;
    
    public class NearestSpawnpoint : MonoBehaviour {
      public GameObject[] respawns;
      public const float FIRE_DELAY = 0.25f;
      private float nextFireTime = 0f;
        
      private void Start(){
        respawns = GameObject.FindGameObjectsWithTag("Respawn");
      }
    
      void Update() {
        if( Time.time > nextFireTime )
          CheckFireKey();
      }
    
      void CheckFireKey() {
        if( Input.GetButton("Fire1")) {
          MoveToNewPosition();
          nextFireTime = Time.time + FIRE_DELAY;
        }
      }
    
      private void MoveToNewPosition(){
        transform.position = NearestSpawnpointPosition();
      }
    
      private Vector3 NearestSpawnpointPosition(){
        if( respawns.Length < 1) return transform.position;
        Vector3 pos = respawns[0].transform.position;
        float shortestDistance = Vector3.Distance( transform.position, pos);
        for(int i = 1; i < respawns.Length; i++){
          Vector3 newPos = respawns[i].transform.position;
          float newDist = Vector3.Distance( transform.position, newPos);
          if( newDist < shortestDistance){
            pos = newPos;
            shortestDistance = newDist;
          }
        }
        
        return pos;
      }
    }
  4. Run your game. Move the red cube around with the arrow keys, and click on the mouse button. The red cube should jump to the nearest capsule spawn point.

How it works...

The Start() and CheckFireKey() methods are the same, except that CheckFireKey() now calls the MoveToNewPosition() method.

The MoveToNewPosition() method has a single statement, setting the position of the (player cube's) transform to the Vector3 location returned from the NearestSpawnpointPosition() method.

The NearestSpawnpointPosition() method has the job of finding and returning the position of the spawn point closest to the current location of the (player cube's) transform. First, a check is made in case no respawn points can be found, in which case the current position of the player's cube is returned. Then, the position of first element in the respawns array is chosen as the first closest spawn point and is stored in the pos variable. The distance from the player cube to this object is stored in the shortestDistance variable. A for loop is used to loop through the remaining spawn points, and each time one is found to be closer than the distance in shortestDistance, then this closer position is stored into pos and the new closer distance stored in shortestDistance. Once all spawn points have been tested, the method returns the Vector3 value in pos.

See also

  • The Finding a random spawn point recipe
  • The Following waypoints in a sequence recipe
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.226.164.75