Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System.Collections;
- using System.Collections.Generic;
- using UnityEngine;
- public class CameraTest : MonoBehaviour {
- [SerializeField] private float timeToMoveCamera;
- [SerializeField] private Rigidbody2D targetRb;
- private Camera cam;
- private Bounds camBounds;
- private Vector3 startMovePosition;
- private Vector3 endMovePosition;
- private float timeMoveStarted;
- private bool isMoving;
- private void Start() {
- cam = GetComponent<Camera>();
- SetCamBounds(transform.position);
- }
- private void SetCamBounds(Vector3 _camPos) {
- float screenHeight = cam.orthographicSize * 2;
- Vector3 boundSize = new Vector3(0f, screenHeight, 0f);
- camBounds = new Bounds(_camPos, boundSize);
- }
- private void StartCameraMoving() {
- startMovePosition = transform.position;
- endMovePosition = new Vector3(transform.position.x, camBounds.min.y - camBounds.size.y / 2, transform.position.z);
- timeMoveStarted = Time.time;
- isMoving = true;
- StopTargetMovement();
- }
- private void Update() {
- if (!isMoving && targetRb.transform.position.y <= camBounds.min.y) {
- StartCameraMoving();
- }
- LerpToNextPosition();
- }
- private void LerpToNextPosition() {
- if (isMoving) {
- float timeSinceMoveStarted = Time.time - timeMoveStarted;
- float moveDistPercentageComplete = timeSinceMoveStarted / timeToMoveCamera;
- transform.position = Vector3.Lerp(startMovePosition, endMovePosition, moveDistPercentageComplete);
- if (moveDistPercentageComplete >= 1.0f) {
- isMoving = false;
- SetCamBounds(transform.position);
- StartTargetMovement();
- }
- }
- }
- Vector2 targetVelBeforeStop = Vector2.zero;
- private void StartTargetMovement() {
- targetRb.velocity = targetVelBeforeStop;
- targetRb.isKinematic = false;
- }
- private void StopTargetMovement() {
- targetVelBeforeStop = targetRb.velocity;
- targetRb.velocity = Vector2.zero;
- targetRb.isKinematic = true;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement