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.
This recipe builds upon the previous one, so make a copy of that Unity project then follow the steps of this recipe.
To find the nearest spawn point, perform the following steps:
SpawnBall
scripted component from the Main Camera.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; } }
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
.
3.145.179.85