Advertisement
Guest User

Untitled

a guest
Aug 18th, 2018
63
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.91 KB | None | 0 0
  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4.  
  5. public class CameraTest : MonoBehaviour {
  6.  
  7. [SerializeField] private float timeToMoveCamera;
  8. [SerializeField] private Rigidbody2D targetRb;
  9.  
  10. private Camera cam;
  11. private Bounds camBounds;
  12.  
  13. private Vector3 startMovePosition;
  14. private Vector3 endMovePosition;
  15. private float timeMoveStarted;
  16. private bool isMoving;
  17.  
  18. private void Start() {
  19. cam = GetComponent<Camera>();
  20. SetCamBounds(transform.position);
  21. }
  22.  
  23. private void SetCamBounds(Vector3 _camPos) {
  24. float screenHeight = cam.orthographicSize * 2;
  25. Vector3 boundSize = new Vector3(0f, screenHeight, 0f);
  26. camBounds = new Bounds(_camPos, boundSize);
  27. }
  28.  
  29. private void StartCameraMoving() {
  30. startMovePosition = transform.position;
  31. endMovePosition = new Vector3(transform.position.x, camBounds.min.y - camBounds.size.y / 2, transform.position.z);
  32. timeMoveStarted = Time.time;
  33. isMoving = true;
  34. StopTargetMovement();
  35. }
  36.  
  37. private void Update() {
  38.  
  39. if (!isMoving && targetRb.transform.position.y <= camBounds.min.y) {
  40. StartCameraMoving();
  41. }
  42.  
  43. LerpToNextPosition();
  44. }
  45.  
  46. private void LerpToNextPosition() {
  47. if (isMoving) {
  48. float timeSinceMoveStarted = Time.time - timeMoveStarted;
  49. float moveDistPercentageComplete = timeSinceMoveStarted / timeToMoveCamera;
  50. transform.position = Vector3.Lerp(startMovePosition, endMovePosition, moveDistPercentageComplete);
  51. if (moveDistPercentageComplete >= 1.0f) {
  52. isMoving = false;
  53. SetCamBounds(transform.position);
  54. StartTargetMovement();
  55. }
  56. }
  57. }
  58.  
  59. Vector2 targetVelBeforeStop = Vector2.zero;
  60.  
  61. private void StartTargetMovement() {
  62. targetRb.velocity = targetVelBeforeStop;
  63. targetRb.isKinematic = false;
  64. }
  65.  
  66. private void StopTargetMovement() {
  67. targetVelBeforeStop = targetRb.velocity;
  68. targetRb.velocity = Vector2.zero;
  69. targetRb.isKinematic = true;
  70. }
  71.  
  72. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement