您现在的位置:首页 >> 前端 >> 内容

摄像机鼠标左键旋转视角,滚轮缩放视角效果实现

时间:2017/8/26 9:32:00 点击:

  核心提示:将此代码挂载 主摄像机上即可 usingUnityEngine;usingSystem.Collections;public class TXCameraFollowPlayer : MonoBeha...

将此代码挂载 主摄像机上即可

 usingUnityEngine;

usingSystem.Collections;



public class TXCameraFollowPlayer : MonoBehaviour {



    public Transform player;//需要旋转的模型

    private Vector3 offset;//偏移量

    private float speed=5f;//缩放视角  速度

    private bool isRotate=false;//是否正在按下右键

    private float rotateSpeed=3;//旋转速度

 private float distance = 0;

    // Use this for initialization

    void Start () {

        offset = transform.position - player.position;

    }



    // Update is called once per frame

    void Update () {

        transform.position = offset + player.position;

        RotateView ();

        ScrollView ();

    }



    void ScrollView(){

        //根据offset用magnitude可以求出两点之间的距离

        distance = offset.magnitude;

        distance += Input.GetAxis ("Mouse ScrollWheel")*speed;

        //将distance控制在2,18之间

        distance = Mathf.Clamp (distance,0.1f,18);

        //normalized是向量

        offset = offset.normalized * distance;

    }

    void RotateView(){

        if(Input.GetMouseButtonDown (1)) {

            isRotate=true;      

        }

        if(Input.GetMouseButtonUp (1)) {

            isRotate=false;     

        }

        if (isRotate) {

            //Vector3 origiPos=transform.position;

            //Quaternion origiRotation=transform.rotation;



            transform.RotateAround(player.position,player.up,Input.GetAxis("Mouse X")*rotateSpeed);

            transform.RotateAround(player.position,transform.right,-Input.GetAxis("Mouse Y")*rotateSpeed);



//          float x=transform.eulerAngles.x;

//          if(x<10||x>80){

//              transform.position=origiPos;

//              transform.rotation=origiRotation;

//          }

        }

        offset = transform.position - player.position;

    }

}

作者:网络 来源:yiwei151的博