Unity相机围绕对象旋转

时间:2018-08-30 17:29:02

标签: c# unity3d unityscript

在我的项目中,我目前有1个脚本,1个摄像机和1个对象。我编写了一个代码(请参阅下文),该代码将使相机围绕对象旋转,但X轴并非总是左右,而Y轴并不总是上下。

我的意思是,例如,如果我们加载成一个整体,并且相机轴为Y =上,X =左,Z为变换位置,并且对象与相机的方向相同。我可以单击并向左或向右/向上或向下拖动,相机将正确旋转,但将其沿任意方向旋转90度后,相反的轴将不会旋转。

我知道“完美轮换”是一个术语,但我不知道该术语,因此我很难解释。抱歉。请随时将代码输入C#脚本并进行操作。将脚本添加到摄像机,确保摄像机正在查看对象,并且需要将该对象添加到脚本上的游戏对象。

有人可以帮助我,以便当我向左滑动时,该对象将始终向左旋转,从右向右旋转,向上旋转,向下旋转向下。

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class FocusObject : MonoBehaviour
{

    public GameObject target;//the target object
    private Vector3 point;//the coord to the point where the camera looks at

    float f_lastX = 0.0f;
    float f_difX = 0.0f;  
    float f_lastY = 0.0f;
    float f_difY = 0.0f;  


    void Start()
    {//Set up things on the start method
        point = target.transform.position;//get target's coords
        transform.LookAt(point);//makes the camera look to it 
    }

    void Update()
    {

        if (Input.GetMouseButtonDown(0))
        {
            f_difX = 0.0f;
            f_difY = 0.0f;
        }
        else if (Input.GetMouseButton(0))
        {
            f_difX = Mathf.Abs(f_lastX - Input.GetAxis("Mouse X"));
            f_difY = Mathf.Abs(f_lastY - Input.GetAxis("Mouse Y"));

            if (f_lastX < Input.GetAxis("Mouse X"))
            {
                transform.RotateAround(point, new Vector3(0.0f, 1.0f, 0.0f), f_difX);
            }

            if (f_lastX > Input.GetAxis("Mouse X"))
            {
                transform.RotateAround(point, new Vector3(0.0f, -1.0f, 0.0f), f_difX);
            }

            if (f_lastY < Input.GetAxis("Mouse Y"))
            {
                transform.RotateAround(point, new Vector3(1.0f, 0.0f, 0.0f), f_difY);
            }

            if (f_lastY > Input.GetAxis("Mouse Y"))
            {
                transform.RotateAround(point, new Vector3(-1.0f, 0.0f, 0.0f), f_difY);

            }

            f_lastX = -Input.GetAxis("Mouse X");
            f_lastY = -Input.GetAxis("Mouse Y");
        }
    }
}

0 个答案:

没有答案