You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

92 lines
2.5 KiB

  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4. public class CustomSmoothFollow : MonoBehaviour
  5. {
  6. public Transform target;
  7. public float distance = -200.0f;
  8. public float height = 200.0f;
  9. public float altDistance = -100.0f;
  10. public float altHeight = 250.0f;
  11. public Vector3 damping;
  12. public string layerToMask = "CameraObstruct";
  13. private int layerMask;
  14. [Range (0,360)]
  15. public float offsetAngle = 90;
  16. // Use this for initialization
  17. void Start()
  18. {
  19. layerMask = LayerMask.NameToLayer(layerToMask);
  20. }
  21. // Update is called once per frame
  22. void LateUpdate()
  23. {
  24. // Early out if we don't have a target
  25. if (!target)
  26. return;
  27. // Calculate the current and wanted height / XZ pos
  28. float wantedHeight = target.position.y + height;
  29. float wantedDistance = target.position.z + distance;
  30. float wantedSide = target.position.x;
  31. bool isBlocked = false;
  32. Vector3 wantedPos = new Vector3(wantedSide, wantedHeight, wantedDistance);
  33. wantedPos = RotatePointAroundPivot(wantedPos, target.transform.position, offsetAngle);
  34. RaycastHit hitInfo;
  35. if (Physics.Raycast(wantedPos, target.position-wantedPos, out hitInfo, (target.position-wantedPos).magnitude * 2f))
  36. {
  37. if (hitInfo.collider.gameObject.layer == layerMask)
  38. isBlocked = true;
  39. }
  40. if (isBlocked)
  41. {
  42. wantedHeight = target.position.y + altHeight;
  43. wantedDistance = target.position.z + altDistance;
  44. }
  45. float currentHeight = transform.position.y;
  46. float currentDistance = transform.position.z;
  47. float currentSide = transform.position.x;
  48. // Damp the height
  49. currentHeight = Mathf.Lerp(currentHeight, wantedPos.y, damping.y * Time.deltaTime);
  50. currentDistance = Mathf.Lerp(currentDistance, wantedPos.z, damping.z * Time.deltaTime);
  51. currentSide = Mathf.Lerp(currentSide, wantedPos.x, damping.x * Time.deltaTime);
  52. // Set the position of the camera on the x-z plane to:
  53. // distance meters behind the target
  54. transform.position = target.position;
  55. // Set the height of the camera
  56. transform.position = new Vector3(currentSide, currentHeight, currentDistance);
  57. // Always look at the target
  58. Vector3 lookTarget = target.position;
  59. lookTarget.z = transform.position.z;
  60. transform.LookAt(lookTarget);
  61. }
  62. private Vector3 RotatePointAroundPivot(Vector3 point,Vector3 pivot,float angles ) {
  63. Vector3 dir = point - pivot; // get point direction relative to pivot
  64. dir = Quaternion.Euler(angles * Vector3.up) * dir; // rotate it
  65. point = dir + pivot; // calculate rotated point
  66. return point; // return it
  67. }
  68. }