Unity之繞軸進行旋轉的操作
先上一張效果圖

using UnityEngine;
using System.Collections;
public class TestRotateRound : MonoBehaviour
{
public GameObject Sphere;
private float curtTime = 0.0f;
void Update()
{
//使用C#封裝好的代碼RotateAround
gameObject.transform.RotateAround(Sphere.transform.position, Sphere.transform.up, 72 * Time.deltaTime);
//自己封裝代碼,功能和上面的相同
//RotateAround(Sphere.transform.position,Vector3.up, 72 * Time.deltaTime);
}
private void RotateAround(Vector3 center, Vector3 axis, float angle)
{
//繞axis軸旋轉angle角度
Quaternion rotation = Quaternion.AngleAxis(angle, axis);
//旋轉之前,以center為起點,transform.position當前物體位置為終點的向量.
Vector3 beforeVector = transform.position - center;
//四元數(shù) * 向量(不能調(diào)換位置, 否則發(fā)生編譯錯誤)
Vector3 afterVector = rotation * beforeVector;//旋轉后的向量
//向量的終點 = 向量的起點 + 向量
transform.position = afterVector + center;
//看向Sphere,使Z軸指向Sphere
transform.LookAt(Sphere.transform.position);
}
}
補充:Unity繞x軸旋轉并限制角度的陷阱

在制作FPS相機時,遇到了需要限制角度的需求,視角只能查看到-60到60度的范圍,而在Unity的Transform組件中,繞x軸逆時針旋轉,Transform組件的localEulerAngle會在0~360范圍內(nèi)遞增(如圖)
關鍵在于其中的角度轉換,直接上代碼
public static void RotateClampX(this Transform t, float degree, float min, float max)
{
degree = (t.localEulerAngles.x - degree);
if (degree > 180f)
{
degree -= 360f;
}
degree = Mathf.Clamp(degree, min, max);
t.localEulerAngles = t.localEulerAngles.SetX(degree);
}
補充:Unity3D 實現(xiàn)物體始終面向另一個物體(繞軸旋轉、四元數(shù)旋轉)
一開始本人糾結于在VR中,怎么利用手柄來控制物體的旋轉,物體位置不變。
相當于:地球儀。更通俗點來說,就是一個棍子插到地球儀上,然后拿著棍子就可以控制地球儀轉。手柄相當于那根棍子。
代碼如下:
myTransform.rotation = Quaternion.Slerp(myTransform.rotation, Quaternion.LookRotation(target.position - myTransform.position), rotationSpeed * Time.deltaTime);
這句代碼實現(xiàn)了 myTransform 始終可以根據(jù) target 旋轉,rotationSpeed控制速度。
當然上面這句話僅僅只是始終面向,還沒有加上一開始記錄下target的初始旋轉。不然一開始就要跟著手柄轉,而不是自己隨意控制。對于上句的理解,我理解完便貼上。
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。如有錯誤或未考慮完全的地方,望不吝賜教。
相關文章
C# HttpClient Post參數(shù)同時上傳文件的實現(xiàn)
這篇文章主要介紹了C# HttpClient Post參數(shù)同時上傳文件的實現(xiàn),具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-06-06
C# 中的 IReadOnlyDictionary 和 IReadOnlyLis
C# 中的IReadOnlyDictionary和IReadOnlyList是接口,用于表示只讀的字典和只讀的列表,這些接口提供了對集合的只讀訪問權限,即不允許對集合進行修改操作,這篇文章主要介紹了C# 中的 IReadOnlyDictionary 和 IReadOnlyList實例詳解,需要的朋友可以參考下2024-03-03
C# WinForm捕獲全局變量異常 SamWang解決方法
本文將介紹C# WinForm捕獲全局變量異常 SamWang解決方法,需要的朋友可以參考2012-11-11

