CameraOrbit.cs 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. /*
  2. This script orbits the camera around a specific object.
  3. Email :: thomas.ir.rasor@gmail.com
  4. */
  5. using UnityEngine;
  6. public class CameraOrbit : MonoBehaviour
  7. {
  8. public Transform target;
  9. public float distance = 2f;
  10. public float lerpSpeed = 3f;
  11. public float scrollSpeed = 5f;
  12. public float minDist = 0.5f;
  13. public float maxDist = 5f;
  14. public bool raycastedDistance = false;
  15. float wdist, cdist;
  16. Vector3 wrot, crot;
  17. Vector3 worigin, corigin;
  18. void Start ()
  19. {
  20. wdist = distance;
  21. transform.position = corigin - transform.forward * wdist;
  22. }
  23. void Update ()
  24. {
  25. float t = Time.deltaTime * 2f * lerpSpeed;
  26. wdist -= Input.GetAxis( "Mouse ScrollWheel" ) * Time.deltaTime * 5f * scrollSpeed;
  27. wdist = Mathf.Clamp( wdist , minDist , maxDist );
  28. cdist = Mathf.Lerp( cdist , wdist , t );
  29. if ( Input.GetMouseButton( 1 ))
  30. {
  31. wrot.y += Input.GetAxis( "Mouse X" ) * 3f;
  32. wrot.x -= Input.GetAxis( "Mouse Y" ) * 3f;
  33. }
  34. wrot.z = 0f;
  35. crot.x = Mathf.LerpAngle( crot.x , wrot.x , t );
  36. crot.y = Mathf.LerpAngle( crot.y , wrot.y , t );
  37. crot.z = Mathf.LerpAngle( crot.z , wrot.z , t );
  38. transform.rotation = Quaternion.Euler( crot );
  39. if ( target != null )
  40. worigin = target.position;
  41. else
  42. worigin = Vector3.zero;
  43. if ( raycastedDistance )
  44. {
  45. RaycastHit h;
  46. Ray r = new Ray( worigin - transform.forward * ( cdist + 1f ) , transform.forward );
  47. if(Physics.Raycast(r,out h))
  48. {
  49. worigin = h.point;
  50. }
  51. }
  52. corigin = Vector3.Lerp( corigin , worigin , t );
  53. transform.position = corigin - transform.forward * cdist;
  54. }
  55. void OnDrawGizmosSelected ()
  56. {
  57. Gizmos.color = Color.red;
  58. Gizmos.DrawWireSphere( worigin , 0.2f );
  59. Gizmos.DrawLine( worigin , transform.position );
  60. Gizmos.color = Color.blue;
  61. Gizmos.DrawWireSphere( corigin , 0.2f );
  62. Gizmos.DrawLine( corigin , transform.position );
  63. }
  64. }