镜头跟随玩家移动

using UnityEngine;
using System.Collections;

/// <summary>
/// 相机跟随玩家
/// </summary>
public class FollowPlayer : MonoBehaviour
{
    private Transform player;
    private Vector3 offsetPosition;
    private float smothing = 5f;
    public float distance = 0;
    public float scrollSpeed = 2;
    private bool isRotaing=false;
    public float RorateSpeed = 1f;
    // Use this for initialization
    void Start()
    {
        player = GameObject.FindGameObjectWithTag("Player").transform;
        transform.LookAt(player);
        offsetPosition = transform.position - player.position;
    }

    // Update is called once per frame
    void Update()
    {
       
        Vector3 targetCampos = player.position + offsetPosition;
        //使用插值到达平滑视觉
        transform.position = Vector3.Lerp(transform.position,targetCampos,smothing*Time.deltaTime);
        //处理视野旋转
        RotateView();
        ScrollView();
    }


    /// <summary>
    /// 镜头拉近拉远
    /// </summary>
    void ScrollView()
    {
        //print(Input.GetAxis("Mouse ScrollWheel"));//向后 返回负值(拉远视野),向前返回正直(拉近视野)
        //offsetPosition.magnitude  返回向量的长度(只读)。
        distance = offsetPosition.magnitude;
        distance += Input.GetAxis("Mouse ScrollWheel")*scrollSpeed;

        //距离限制
        distance = Mathf.Clamp(distance,4,14);
     
        //offsetPosition.normalized  返回向量的长度为1(只读)。
        offsetPosition = offsetPosition.normalized * distance;
    }

    /// <summary>
    /// 旋转视角
    /// </summary>
    void RotateView()
    {
     //   Input.GetAxis("Mouse X");//得到鼠标在X水平方向滑动
     //   Input.GetAxis("Mouse Y");//得到鼠标在Y水平方向滑动
        if (Input.GetMouseButtonDown(0))
        {
            isRotaing = true;
        }
        if (Input.GetMouseButtonUp(0))
        {
            isRotaing = false;
        }

        if (isRotaing)
        {
            transform.RotateAround(player.position, player.up, RorateSpeed * Input.GetAxis("Mouse X"));  //左右

            Vector3 originalPos = transform.position;
            Quaternion originalRotation = transform.rotation;
            transform.RotateAround(player.position, transform.right, -RorateSpeed * Input.GetAxis("Mouse Y"));//上下
            float x = transform.eulerAngles.x;
            if(x<10 || x > 80)//当超出范围我们将属性 归为原来得
            {
                transform.position = originalPos;
                transform.rotation = originalRotation;
            }
            offsetPosition = transform.position - player.position;
        }
      
    }   
}

 

posted @ 2017-02-08 20:18  RONGWEIJUN  阅读(458)  评论(0编辑  收藏  举报