c# - 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 - C程序输出数组列表,然后在列表之间交换元素并再次输出
- css - 如何在 a 上实现鼠标悬停
- 在 VueJS 中?
- android - 了解可滚动 GridView 中 Cardview 中的解决方法
- spring - Spring mvc web 服务给出 Content-Type →text/html;charset=ISO-8859-1 预期为 [{"key":"Content-Type","value":"application/json"}]
- c++ - C++ DLL 引用来自 C++.exe 的函数和类
- python - 如何连接众多df的熊猫
- swift - Swift 4——尝试使用泛型来减少公式化代码的挑战
- css - 为什么 2 个 div 之间的风格不同?
- javascript - 谷歌扩展如何点击网页上的按钮?
- android - Android Room:将 json 结果转换为 db 对象的有效方法