Unity之繞軸進行旋轉(zhuǎn)的操作
先上一張效果圖
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軸旋轉(zhuǎn)angle角度 Quaternion rotation = Quaternion.AngleAxis(angle, axis); //旋轉(zhuǎn)之前,以center為起點,transform.position當前物體位置為終點的向量. Vector3 beforeVector = transform.position - center; //四元數(shù) * 向量(不能調(diào)換位置, 否則發(fā)生編譯錯誤) Vector3 afterVector = rotation * beforeVector;//旋轉(zhuǎn)后的向量 //向量的終點 = 向量的起點 + 向量 transform.position = afterVector + center; //看向Sphere,使Z軸指向Sphere transform.LookAt(Sphere.transform.position); } }
補充:Unity繞x軸旋轉(zhuǎn)并限制角度的陷阱
在制作FPS相機時,遇到了需要限制角度的需求,視角只能查看到-60到60度的范圍,而在Unity的Transform組件中,繞x軸逆時針旋轉(zhuǎn),Transform組件的localEulerAngle會在0~360范圍內(nèi)遞增(如圖)
關(guān)鍵在于其中的角度轉(zhuǎn)換,直接上代碼
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)物體始終面向另一個物體(繞軸旋轉(zhuǎn)、四元數(shù)旋轉(zhuǎn))
一開始本人糾結(jié)于在VR中,怎么利用手柄來控制物體的旋轉(zhuǎn),物體位置不變。
相當于:地球儀。更通俗點來說,就是一個棍子插到地球儀上,然后拿著棍子就可以控制地球儀轉(zhuǎn)。手柄相當于那根棍子。
代碼如下:
myTransform.rotation = Quaternion.Slerp(myTransform.rotation, Quaternion.LookRotation(target.position - myTransform.position), rotationSpeed * Time.deltaTime);
這句代碼實現(xiàn)了 myTransform 始終可以根據(jù) target 旋轉(zhuǎn),rotationSpeed控制速度。
當然上面這句話僅僅只是始終面向,還沒有加上一開始記錄下target的初始旋轉(zhuǎn)。不然一開始就要跟著手柄轉(zhuǎn),而不是自己隨意控制。對于上句的理解,我理解完便貼上。
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。如有錯誤或未考慮完全的地方,望不吝賜教。
相關(guān)文章
Unity基于ShaderLab實現(xiàn)光照系統(tǒng)(著色器代碼實現(xiàn)小結(jié))
這篇文章主要介紹了Unity基于ShaderLab實現(xiàn)光照系統(tǒng),主要總結(jié)unity中shaderlab的著色器代碼實現(xiàn),本文給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2022-01-01C#入門之checked和unchecked的區(qū)別實例解析
這篇文章主要介紹了C#中checked和unchecked的區(qū)別,是學習C#必須要牢固掌握的,需要的朋友可以參考下2014-08-08