鼠标右键控制视角移动,滚轮控制视角远近。
public class FollowPlayer : MonoBehaviour
{
public float distance = 0;
private Transform player;
private Vector3 offset;
private float scrollSpeed = 5;
private bool isRotating = false;
// Use this for initialization
void Start()
{
player = GameObject.FindGameObjectWithTag(Tags.player).transform;
transform.LookAt(player);
offset = transform.position - player.position;
}
// Update is called once per frame
void Update()
{
transform.position = player.position + offset;
RotateView();
ScrollView();
}
void ScrollView()
{
distance = offset.magnitude;
distance -= Input.GetAxis("Mouse ScrollWheel") * scrollSpeed;
distance = Mathf.Clamp(distance, 5, 18);
offset = offset.normalized * distance;
}
void RotateView()
{
if (Input.GetMouseButtonDown(1))
{
isRotating = true;
}
if (Input.GetMouseButtonUp(1))
{
isRotating = false;
}
if (isRotating)
{
Vector3 originalPos = transform.position;
Quaternion originalRotation = transform.rotation;
transform.RotateAround(player.position, player.up, Input.GetAxis("Mouse X"));
transform.RotateAround(player.position, transform.right, -Input.GetAxis("Mouse Y"));
// 影响了position和rotation
//限制视角上下移动的范围
float x = transform.eulerAngles.x;
if (x < 10 || x > 80)
{
transform.position = originalPos;
transform.rotation = originalRotation;
}
}
offset = transform.position - player.position;
}
}