上QQ阅读APP看书,第一时间看更新
How to do it...
We can now proceed to implement our facing algorithm that derives from Align:
- Create the Face class along with a private auxiliary target member variable:
using UnityEngine; using System.Collections; public class Face : Align { protected GameObject targetAux; }
- Override the Awake function to set up everything and swap references:
public override void Awake() { base.Awake(); targetAux = target; target = new GameObject(); target.AddComponent<Agent>(); }
- Also, implement the OnDestroy function to handle references and avoid memory issues:
void OnDestroy () { Destroy(target); }
- Finally, define the GetSteering function:
public override Steering GetSteering() { Vector3 direction = targetAux.transform.position - transform.position; if (direction.magnitude > 0.0f) { float targetOrientation = Mathf.Atan2(direction.x, direction.z); targetOrientation *= Mathf.Rad2Deg; target.GetComponent<Agent>().orientation = targetOrientation; } return base.GetSteering(); }