Advertisement
thegreen9

Cameras

Oct 17th, 2018
120
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 2.37 KB | None | 0 0
  1. using UnityEngine;
  2.  
  3. namespace Cameras
  4. {
  5.     [RequireComponent(typeof(Camera))]
  6.     public class FollowingCamera2D : MonoBehaviour
  7.     {
  8.         public float DampTime;
  9.         public Transform Target;
  10.         public Vector3 Offset;
  11.  
  12.         private new Camera camera;
  13.         private Vector3 velocity = Vector3.zero;
  14.  
  15.         public bool AllowedPositiveX = true;
  16.         public bool AllowedNegativeX = true;
  17.         public bool AllowedPositiveY = true;
  18.         public bool AllowedNegativeY = true;
  19.  
  20.         public Vector3 UpperPositionLimit = new Vector3(float.MaxValue, float.MaxValue, float.MaxValue);
  21.         public Vector3 LowerPositionLimit = new Vector3(float.MinValue, float.MinValue, float.MinValue);
  22.  
  23.         private void Awake()
  24.         {
  25.             camera = GetComponent<Camera>();
  26.         }
  27.  
  28.         // Update is called once per frame
  29.         private void LateUpdate()
  30.         {
  31.             if (Target)
  32.             {
  33.                 var targetPosition = Target.position;
  34.  
  35.                 targetPosition.x = Mathf.Clamp(targetPosition.x, LowerPositionLimit.x, UpperPositionLimit.x);
  36.                 targetPosition.y = Mathf.Clamp(targetPosition.y, LowerPositionLimit.y, UpperPositionLimit.y);
  37.                 targetPosition.z = Mathf.Clamp(targetPosition.z, LowerPositionLimit.z, UpperPositionLimit.z);
  38.  
  39.                 targetPosition += Offset;
  40.  
  41.                 var targetViewportPosition = camera.WorldToViewportPoint(targetPosition);
  42.                 var delta = targetPosition -
  43.                             camera.ViewportToWorldPoint(new Vector3(0.5f, 0.5f, targetViewportPosition.z));
  44.                 var oldPosition = transform.position;
  45.                 var destination = oldPosition + delta;
  46.                 if (!AllowedPositiveX && destination.x > oldPosition.x ||
  47.                     !AllowedNegativeX && destination.x < oldPosition.x)
  48.                 {
  49.                     destination.x = oldPosition.x;
  50.                 }
  51.  
  52.                 if (!AllowedPositiveY && destination.y > oldPosition.y ||
  53.                     !AllowedNegativeY && destination.y < oldPosition.y)
  54.                 {
  55.                     destination.y = oldPosition.y;
  56.                 }
  57.  
  58.                 var newPosition = Vector3.SmoothDamp(oldPosition, destination, ref velocity, DampTime);
  59.  
  60.                 transform.position = newPosition;
  61.             }
  62.         }
  63.     }
  64. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement