您的位置:首页 > 移动开发 > Unity3D

Unity实现摄像机围绕物体旋转

2017-10-20 17:17 585 查看
rotateY和rotateX的初始坐标与要围绕旋转的物体坐标一致,比如(0,0,0)

using System.Collections;

using System.Collections.Generic;

using UnityEngine;

public class CameraCtrl : MonoBehaviour

{

    public GameObject rotateY;

    public GameObject rotateX;

    private Quaternion targetTransY;

    private Quaternion targetTransX;

    private float mouseY;

    private float mouseX;

    private float YAngleChange;

    private float XAngleChange;

    private float smoothSpeed = 10f;

    void Update()

    {

        if (Input.GetMouseButton(0))

        {

            mouseX = Input.GetAxis("Mouse X");

            mouseY = Input.GetAxis("Mouse Y");

            RotateByX(mouseY);

            RotateByY(mouseX);

        }

    }

    void RotateByY(float xValue)

    {

        YAngleChange += xValue * smoothSpeed * Time.deltaTime * 90;

        targetTransY = Quaternion.Euler(0, YAngleChange, 0);

        rotateY.transform.localRotation = Quaternion.Slerp(rotateY.transform.localRotation, targetTransY, 2);

    }

    void RotateByX(float yValue)

    {

        XAngleChange -= yValue * smoothSpeed * Time.deltaTime * 90;

        XAngleChange = Mathf.Clamp(XAngleChange, -70f, 40f);

        targetTransX = Quaternion.Euler(XAngleChange, 0, 0);

        rotateX.transform.localRotation = Quaternion.Slerp(rotateX.transform.localRotation, targetTransX, 2);

    }

    //  也可以实现

    //void RotateByYT(float xValue)

    //{

    //    rotateY.transform.Rotate(Vector3.up * xValue * Time.deltaTime * smoothSpeed);

    //}

    //void RotateByXT(float yValue)

    //{

    //    rotateX.transform.Rotate(Vector3.right * yValue * Time.deltaTime * smoothSpeed * (-1));

    //}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: