CameraFollow.cs 3.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. using System;
  2. using UnityEngine;
  3. namespace UnityStandardAssets._2D
  4. {
  5. public class CameraFollow : MonoBehaviour
  6. {
  7. public float xMargin = 1f; // Distance in the x axis the player can move before the camera follows.
  8. public float yMargin = 1f; // Distance in the y axis the player can move before the camera follows.
  9. public float xSmooth = 8f; // How smoothly the camera catches up with it's target movement in the x axis.
  10. public float ySmooth = 8f; // How smoothly the camera catches up with it's target movement in the y axis.
  11. public Vector2 maxXAndY; // The maximum x and y coordinates the camera can have.
  12. public Vector2 minXAndY; // The minimum x and y coordinates the camera can have.
  13. private Transform m_Player; // Reference to the player's transform.
  14. private void Awake()
  15. {
  16. // Setting up the reference.
  17. m_Player = GameObject.FindGameObjectWithTag("Player").transform;
  18. }
  19. private bool CheckXMargin()
  20. {
  21. // Returns true if the distance between the camera and the player in the x axis is greater than the x margin.
  22. return Mathf.Abs(transform.position.x - m_Player.position.x) > xMargin;
  23. }
  24. private bool CheckYMargin()
  25. {
  26. // Returns true if the distance between the camera and the player in the y axis is greater than the y margin.
  27. return Mathf.Abs(transform.position.y - m_Player.position.y) > yMargin;
  28. }
  29. private void Update()
  30. {
  31. TrackPlayer();
  32. }
  33. private void TrackPlayer()
  34. {
  35. // By default the target x and y coordinates of the camera are it's current x and y coordinates.
  36. float targetX = transform.position.x;
  37. float targetY = transform.position.y;
  38. // If the player has moved beyond the x margin...
  39. if (CheckXMargin())
  40. {
  41. // ... the target x coordinate should be a Lerp between the camera's current x position and the player's current x position.
  42. targetX = Mathf.Lerp(transform.position.x, m_Player.position.x, xSmooth*Time.deltaTime);
  43. }
  44. // If the player has moved beyond the y margin...
  45. if (CheckYMargin())
  46. {
  47. // ... the target y coordinate should be a Lerp between the camera's current y position and the player's current y position.
  48. targetY = Mathf.Lerp(transform.position.y, m_Player.position.y, ySmooth*Time.deltaTime);
  49. }
  50. // The target x and y coordinates should not be larger than the maximum or smaller than the minimum.
  51. targetX = Mathf.Clamp(targetX, minXAndY.x, maxXAndY.x);
  52. targetY = Mathf.Clamp(targetY, minXAndY.y, maxXAndY.y);
  53. // Set the camera's position to the target position with the same z component.
  54. transform.position = new Vector3(targetX, targetY, transform.position.z);
  55. }
  56. }
  57. }