Follow.cs 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. /*
  2. * Enabling the gameObject to follow the target
  3. *
  4. * Author: Jingyi Jia
  5. *
  6. */
  7. using System.Collections;
  8. using System.Collections.Generic;
  9. using UnityEngine;
  10. public class Follow : MonoBehaviour
  11. {
  12. public GameObject Target;
  13. public float offset = 0;
  14. public bool update = false;
  15. public float MaxDistance = 1;
  16. public int MaxAngle = 360;
  17. // Start is called before the first frame update
  18. private void Awake() {
  19. if(Target == null){
  20. Debug.Log("Set Default Target.");
  21. Target = GameObject.FindGameObjectWithTag("MainCamera");
  22. }
  23. }
  24. void OnEnable()
  25. {
  26. transform.position = Target.transform.position + new Vector3(0, 0, Target.transform.forward.z * offset);
  27. changeDirection();
  28. }
  29. // Update is called once per frame
  30. void Update(){
  31. if(update && Target!=null){
  32. follow();
  33. }
  34. }
  35. public void changeDirection(){
  36. Vector3 direction = Target.transform.eulerAngles;
  37. direction.x = 0;
  38. direction.z = 0;
  39. transform.eulerAngles = direction;
  40. }
  41. public void follow(){
  42. Vector3 pos = Target.transform.position + new Vector3(0, 0, Target.transform.forward.z * offset);
  43. float distance = Vector3.Distance(pos, transform.position);
  44. float angle = Quaternion.Angle(transform.rotation, Target.transform.rotation);
  45. if (distance > MaxDistance || angle > MaxAngle)
  46. {
  47. transform.position = Target.transform.position + new Vector3(0, 0, Target.transform.forward.z * offset);
  48. //changeDirection();
  49. }
  50. }
  51. }