unity3d简单的相机跟随及视野旋转缩放

1、实现相机跟随主角运动

  一种简单的方法是把Camera直接拖到Player下面作为Player的子物体,另一种方法是取得Camera与Player的偏移向量,并据此设置Camera位置,便能实现简单的相机跟随了。

  这里我们选取第二种方法,首先给Camera添加一个脚本,取名为FollowPlayer,脚本很简单不做说明了 

 public class FollowPlayer : MonoBehaviour {

         private Transform player;
private Vector3 offsetPosition; // Use this for initialization
void Start () {
player = GameObject.FindGameObjectWithTag(“Player”).transform;
offsetPosition = transform.position - player.position;
transform.LookAt(player.position);
} // Update is called once per frame
void Update () {
transform.position = offsetPosition + player.position; }

2、视野的缩放

  鼠标滚轮向前拉近视野,向后视野变远。原理是设置一个变量distance为偏移向量的模,鼠标滚轮滑动改变distance的值,然后根据distance设置Camera的位置

  其中scrollSpeed为定义的一个float变量用于调整缩放的速度

 private float distance;

 private void ScrollView()
{
distance = offsetPosition.magnitude;
//向前滑动拉近 向后滑动拉远
distance -= Input.GetAxis("Mouse ScrollWheel") * scrollSpeed;
distance = Mathf.Clamp(distance, MinDistance, MaxDistance);
offsetPosition = offsetPosition.normalized * distance;
} //然后在Update里面调用ScrollView方法

3、视野旋转

  采用transform.RotateAround方法,让Camera根据Player的位置旋转

  

 private void RotateView()
{
//鼠标右键按下可以旋转视野
if (Input.GetMouseButtonDown())
isRotating = true;
if (Input.GetMouseButtonUp())
isRotating = false; if (isRotating)
{
Vector3 originalPosition = transform.position;
Quaternion originalRotation = transform.rotation;
transform.RotateAround(player.position, player.up, rotateSpeed * Input.GetAxis("Mouse X"));
transform.RotateAround(player.position, transform.right, -rotateSpeed * Input.GetAxis("Mouse Y"));
float x = transform.eulerAngles.x;
//旋转的范围为10度到80度
if (x < || x > )
{
transform.position = originalPosition;
transform.rotation = originalRotation;
} } offsetPosition = transform.position - player.position;
}
上一篇:使ie6/7/8支持css3的方法


下一篇:解决浏览器background-image属性不支持css3动画