首页 > 解决方案 > Unity 相机围绕对象旋转

问题描述

在我的项目中,我目前有 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");
        }
    }
}

标签: c#unity3d

解决方案


推荐阅读