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.

70 lines
2.1 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. // Use this for initialization
  15. void Start()
  16. {
  17. layerMask = LayerMask.NameToLayer(layerToMask);
  18. }
  19. // Update is called once per frame
  20. void LateUpdate()
  21. {
  22. // Early out if we don't have a target
  23. if (!target)
  24. return;
  25. // Calculate the current and wanted height / XZ pos
  26. float wantedHeight = target.position.y + height;
  27. float wantedDistance = target.position.z + distance;
  28. float wantedSide = target.position.x;
  29. bool isBlocked = false;
  30. Vector3 wantedPos = new Vector3(wantedSide, wantedHeight, wantedDistance);
  31. RaycastHit hitInfo;
  32. if (Physics.Raycast(wantedPos, target.position-wantedPos, out hitInfo, (target.position-wantedPos).magnitude * 2f))
  33. {
  34. if (hitInfo.collider.gameObject.layer == layerMask)
  35. isBlocked = true;
  36. }
  37. if (isBlocked)
  38. {
  39. wantedHeight = target.position.y + altHeight;
  40. wantedDistance = target.position.z + altDistance;
  41. }
  42. float currentHeight = transform.position.y;
  43. float currentDistance = transform.position.z;
  44. float currentSide = transform.position.x;
  45. // Damp the height
  46. currentHeight = Mathf.Lerp(currentHeight, wantedHeight, damping.y * Time.deltaTime);
  47. currentDistance = Mathf.Lerp(currentDistance, wantedDistance, damping.z * Time.deltaTime);
  48. currentSide = Mathf.Lerp(currentSide, wantedSide, damping.x * Time.deltaTime);
  49. // Set the position of the camera on the x-z plane to:
  50. // distance meters behind the target
  51. transform.position = target.position;
  52. // Set the height of the camera
  53. transform.position = new Vector3(currentSide, currentHeight, currentDistance);
  54. // Always look at the target
  55. Vector3 lookTarget = target.position;
  56. lookTarget.x = transform.position.x;
  57. transform.LookAt(lookTarget);
  58. }
  59. }