using UnityEngine;
using System.Collections;
///
///将此脚本附加到任意镜头上,可以使其拥有WOW镜头的控制方式
///
public class WowCamera: MonoBehaviour
{
///镜头的目标-player
///
private Transform _target;
///镜头离目标的距离
///
public float Distance = 17.0f;
///最小镜头距离
///
public float MinDistance = 3.0f;
///最大镜头距离
///
public float MaxDistance = 30.0f;
//鼠标滚轮拉近拉远速度系数
public float ScrollFactor = 10.0f;
///左右旋转速度可以快一点
///
public float RotateFactorX = 10.0f;
///上下旋转速度可以慢一点
///
public float RotateFactorY = 0.5f;
//镜头水平环绕角度
public float HorizontalAngle = 0;
//镜头竖直环绕角度
public float VerticalAngle = 20;
public float MaxVerticalAngle = 30;
public float MinVerticalAngle = 6;
private Transform _cameraTransform;
void Start()
{
_cameraTransform = transform;
_target = GameObject.FindGameObjectWithTag ( Tags.Player ).transform;
if ( _target == null)
{
Debug.Log ( "Target Object Not Exist");
}
}
void Update()
{
Distance -= Input.GetAxis ("Mouse ScrollWheel") * ScrollFactor;
Distance = ( Distance < MinDistance ) ? MinDistance : Distance;
Distance = ( Distance > MaxDistance ) ? MaxDistance : Distance;
//按住鼠标左右键移动,镜头随之旋转
var isMouseLeftButtonDown = Input.GetMouseButton(0);
var isMouseRightButtonDown = Input.GetMouseButton(1);
if (isMouseLeftButtonDown || isMouseRightButtonDown)
{
//水平旋转和上下旋转
Screen.lockCursor = true;
var axisX = Input.GetAxis( "Mouse X" );
var axisY = Input.GetAxis( "Mouse Y" );
HorizontalAngle += axisX * RotateFactorX;
VerticalAngle += axisY * RotateFactorY;
VerticalAngle = ( VerticalAngle < MinVerticalAngle ) ? MinVerticalAngle : VerticalAngle;
VerticalAngle = ( VerticalAngle > MaxVerticalAngle ) ? MaxVerticalAngle : VerticalAngle;
if (isMouseRightButtonDown)
{
//如果是鼠标右键移动,则旋转人物在水平面上与镜头方向一致
_target.rotation = Quaternion.Euler(0, HorizontalAngle, 0);
}
}
else
{
Screen.lockCursor = false;
}
///按镜头距离调整位置和方向
var rotation = Quaternion.Euler(VerticalAngle, HorizontalAngle, 0);
var offset = rotation * Vector3.back * Distance;
_cameraTransform.position = _target.position + offset;
_cameraTransform.rotation = rotation;
}
}