CameraManager.cs 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4. public class CameraManager : MonoBehaviour
  5. {
  6. public float damping = 1.5f;
  7. public Vector2 offset = new Vector2(2f, 1f);
  8. public bool faceLeft;
  9. private Transform player;
  10. private int lastX;
  11. void Start()
  12. {
  13. offset = new Vector2(Mathf.Abs(offset.x), offset.y);
  14. FindPlayer(faceLeft);
  15. }
  16. public void FindPlayer(bool playerFaceLeft)
  17. {
  18. player = GameObject.FindGameObjectWithTag("Player").transform;
  19. lastX = Mathf.RoundToInt(player.position.x);
  20. if (playerFaceLeft)
  21. {
  22. transform.position = new Vector3(player.position.x - offset.x, player.position.y + offset.y, transform.position.z);
  23. }
  24. else
  25. {
  26. transform.position = new Vector3(player.position.x + offset.x, player.position.y + offset.y, transform.position.z);
  27. }
  28. }
  29. void Update()
  30. {
  31. if (player)
  32. {
  33. int currentX = Mathf.RoundToInt(player.position.x);
  34. if (currentX > lastX) faceLeft = false; else if (currentX < lastX) faceLeft = true;
  35. lastX = Mathf.RoundToInt(player.position.x);
  36. Vector3 target;
  37. if (faceLeft)
  38. {
  39. target = new Vector3(player.position.x - offset.x, player.position.y + offset.y, transform.position.z);
  40. }
  41. else
  42. {
  43. target = new Vector3(player.position.x + offset.x, player.position.y + offset.y, transform.position.z);
  44. }
  45. Vector3 currentPosition = Vector3.Lerp(transform.position, target, damping * Time.deltaTime);
  46. transform.position = currentPosition;
  47. }
  48. }
  49. }