Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System.Collections;
- using UnityEngine;
- public class CameraController : MonoBehaviour
- {
- private Quaternion rotation = Quaternion.identity; //Creates a quaternion with only zeros (x=0, y=0, z=0, w=0)
- public Transform target; //the player the camera should follow
- public float height; //how heigh the camera should be away from player
- private float speedX; //mouse X
- private float speedY; //mouse Y
- public float horizontalSpeed = 200;//basically some kind of sensitivity (200 worked best for me)
- public float verticalSpeed = 200; //basically some kind of sensitivity (200 worked best for me)
- private float finalDistance;
- public float maxDistance = 5; //maximum distance camera should be away from player
- public float minDistance = 0.5; //minimum distance camera should be away from player
- private void Start()
- {
- }
- private void Update()
- {
- GetInput(); // update speedX and speedY
- NormalRotation(); //set rotation based off mouse
- CalculateFinalPosition(); //calculate camera position
- }
- private void CalculateFinalPosition()
- {
- //Setup temporary variables
- RaycastHit hit;
- Vector3 targetPosition = target.position + target.up * height;
- Vector3 direction = (transform.position - targetPosition).normalized;
- finalDistance = maxDistance;
- //Check collision
- if (Physics.Raycast(targetPosition, direction, out hit, Mathf.Infinity)) { finalDistance = hit.distance - 0.1f; }
- //Apply position
- finalDistance = Mathf.Clamp(finalDistance, minDistance, maxDistance);
- transform.position = (target.position + target.up * height) - transform.forward * finalDistance;
- }
- public void GetInput()
- {
- speedX = Input.GetAxis("Mouse X");
- speedY = Input.GetAxis("Mouse Y");
- print(speedX);
- print(speedY);
- }
- private void NormalRotation()
- {
- //Set rotation values
- rotation.x += speedX * horizontalSpeed * Time.deltaTime;
- rotation.y += speedY * verticalSpeed * Time.deltaTime;
- rotation.y = Mathf.Clamp(rotation.y, -50, 90);
- //Apply rotation
- transform.rotation = Quaternion.Euler(rotation.y, rotation.x, rotation.z);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement