- Home /
Question by
v-bamatt · Oct 01, 2016 at 06:56 AM ·
scripting problemcamera rotation
Smooth Camera Orbit + Inertia with Mouse Drag/Touch
Hi,
I'm trying to get my camera to orbit a target using both mouse controls and touch controls, and have inertia so it keeps moving after I let go of the mouse or screen. This is for Unity 5.4.0f3
Bonus Question: Is there's a way to limit the camera from completely going below the target?
The below script works with out touch and does not have inertia.
Any help will be greatly appreciated.
using UnityEngine;
using System.Collections;
[AddComponentMenu("Camera-Control/Mouse Orbit with zoom")]
public class MouseOrbit : MonoBehaviour {
public Transform target;
public float distance = 5.0f;
public float xSpeed = 80.0f;
public float ySpeed = 80.0f;
public float yMinLimit = -20f;
public float yMaxLimit = 80f;
public float distanceMin = .5f;
public float distanceMax = 15f;
private Rigidbody rigidbody;
float x = 0.0f;
float y = 0.0f;
// Use this for initialization
void Start ()
{
Vector3 angles = transform.eulerAngles;
x = angles.y;
y = angles.x;
rigidbody = GetComponent<Rigidbody>();
// Make the rigid body not change rotation
if (rigidbody != null)
{
rigidbody.freezeRotation = true;
}
}
void LateUpdate ()
{
if (Input.GetMouseButton(0))
{
x += Input.GetAxis("Mouse X") * xSpeed * distance * 0.01f;
y -= Input.GetAxis("Mouse Y") * ySpeed * 0.01f;
y = ClampAngle(y, yMinLimit, yMaxLimit);
Quaternion rotation = Quaternion.Euler(y, x, 0);
distance = Mathf.Clamp(distance - Input.GetAxis("Mouse ScrollWheel")*5, distanceMin, distanceMax);
RaycastHit hit;
if (Physics.Linecast (target.position, transform.position, out hit))
{
distance -= hit.distance;
}
Vector3 negDistance = new Vector3(0.0f, 0.0f, -distance);
Vector3 position = rotation * negDistance + target.position;
transform.rotation = rotation;
transform.position = position;
}
}
public static float ClampAngle(float angle, float min, float max)
{
if (angle < -360F)
angle += 360F;
if (angle > 360F)
angle -= 360F;
return Mathf.Clamp(angle, min, max);
}
}
Comment