using UnityEngine; using System.Collections; public class Camera3D : MonoBehaviour { public GameObject Target; float Distance = 9.0f; float RotationVelocityX; float RotationVelocityY; float RotationSpeedX = 25.0f; float RotationSpeedY = 25.0f; float ZoomVelocity; float ZoomSpeed = 20.0f; float ZoomMin = 7.2f, ZoomMax = 15f; float RotationLimitY = 90; float AngleX; float AngleY; private Quaternion Rotation; void Start() { var angles = transform.eulerAngles; AngleX = angles.y; AngleY = angles.x; } public void SetTarget(GameObject target) { Target = target; } void FixedUpdate() { if (Target) { // Rotate if (Input.GetMouseButton(1)) { RotationVelocityX += Input.GetAxis("Mouse X") * RotationSpeedX * Time.deltaTime; RotationVelocityY += Input.GetAxis("Mouse Y") * RotationSpeedY * Time.deltaTime; } AngleX += RotationVelocityX; AngleY -= RotationVelocityY; AngleY = ClampAngle(AngleY, -RotationLimitY, RotationLimitY); Rotation = Quaternion.Euler(AngleY, AngleX, 0); RotationVelocityX = Mathf.Lerp(RotationVelocityX, 0, 0.1f); RotationVelocityY = Mathf.Lerp(RotationVelocityY, 0, 0.1f); // Zoom float scroll = Input.GetAxis("Mouse ScrollWheel"); ZoomVelocity += Time.deltaTime * scroll * ZoomSpeed; Distance += ZoomVelocity; ZoomVelocity = Mathf.Lerp(ZoomVelocity, 0, 0.1f); // if (Input.GetKey (KeyCode.Z)) { // Distance -= Time.deltaTime * ZoomSpeed; //} else if (Input.GetKey (KeyCode.A)) { // Distance += Time.deltaTime * ZoomSpeed; //} Distance = Mathf.Clamp(Distance, ZoomMin, ZoomMax); transform.Translate(0, 0, Distance); // Position transform.rotation = Rotation; transform.position = Rotation * new Vector3(0.0f, 0.0f, -Distance) + Target.Center; } } static float ClampAngle(float angle, float min, float max) { if (angle < -360) angle += 360; if (angle > 360) angle -= 360; return Mathf.Clamp(angle, min, max); } }