Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using UnityEngine;
- using System.Collections;
- public class CameraBehaviour : MonoBehaviour {
- public Transform target;
- public float distance = 3.0f;
- public float minDistance = 1.0f;
- public float height = 2.0f;
- public float smooth = 3.0f;
- public float zoomSmooth = 25.0f;
- public LayerMask collideLayers;
- void LateUpdate () {
- //Early out if there's no target
- if (!target) {
- Debug.LogWarning ("The camera behaviour script doesn't have an target to follow");
- return;
- }
- //Calculate the position to go if there's nothing in front of camera
- Vector3 wantedPos = target.position;
- wantedPos = target.forward * (-distance) + wantedPos;
- wantedPos.y = target.position.y + height;
- //Check if there is something in front of camera and return hit info
- RaycastHit hit = new RaycastHit ();
- bool isColliding = Physics.Linecast (target.position,
- wantedPos,
- out hit,
- collideLayers);
- //Add a little less distance from collision point to avoid camera entering meshes
- hit.point += transform.TransformDirection (Vector3.forward) * 0.05f;
- //If there isn't anything in front of camera, then go to the calculate position
- if (!isColliding) {
- transform.position = Vector3.Slerp (transform.position,
- wantedPos,
- smooth * Time.deltaTime);
- }
- //Else if there is and the hit distance is grater than min distance, go to hit point
- else if (hit.distance > minDistance){
- transform.position = Vector3.Slerp (transform.position, hit.point ,zoomSmooth * Time.deltaTime);
- }
- //Else if there's something in front of camera and the distance is smaller than hit distance,
- //check if there's something above target, if there is, go to the hit point above target
- //else go (min distance * 2) up
- else {
- //Create a vector3 to check the collision up
- Vector3 upVector = target.position;
- upVector.y += minDistance * 2;
- isColliding = Physics.Linecast (target.position,
- upVector,
- out hit,
- collideLayers);
- hit.point -= transform.TransformDirection (Vector3.forward) * 0.12f;
- if (isColliding)
- transform.position = Vector3.Slerp (transform.position, hit.point ,zoomSmooth * Time.deltaTime);
- else
- transform.position = Vector3.Slerp (transform.position, upVector ,zoomSmooth * Time.deltaTime);
- //Draw linecast on editor
- Debug.DrawLine (target.position, upVector, Color.red);
- }
- //Always look at target
- transform.LookAt (target.position);
- //Draw linecast on editor
- Debug.DrawLine (target.position, wantedPos, Color.black);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement