Unity3D讓物體始終朝向攝像機的2中方法
阿新 • • 發佈:2019-02-13
1、設定rotation
此方法的基礎是將物件繫結在場景中的一個物件上,然後設定物件的rotation或者lookat,需要在Update中時時更新
上面列出了3中設定方法,物件的初始化方法如下://方法1 //m_Name.transform.LookAt(Camera.main.transform.position); //m_Name.transform.rotation = Quaternion.Slerp(Quaternion.LookRotation(Camera.main.transform.position - m_Name.transform.position), m_Name.transform.rotation, 10 * Time.deltaTime); //方法2 //Vector3 v = Camera.main.transform.forward; //m_Name.transform.forward = v; //m_Name.transform.forward = Vector3.Slerp (m_Name.transform.forward,v,10*Time.deltaTime); //方法3 lastRotation = m_cameraTransform.rotation; m_Name.transform.rotation = lastRotation;
headShowObj = new GameObject("playerName"); objTrans = headShowObj.transform; objTrans.parent = _controller.trans;// Camera.main.transform; objTrans.localPosition = Vector3.zero + v; objTrans.localRotation = Quaternion.identity; objTrans.localScale = Vector3.one; objTrans.LookAt(Camera.main.transform.position); m_Name = headShowObj.AddComponent<TextMeshPro>(); m_Name.font = Resources.Load ("UI/Fonts/SIMLI",typeof(TextMeshProFont)) as TextMeshProFont; m_Name.fontSize = 4; m_Name.isOverlay = true; m_Name.alignment = AlignmentTypes.Center; m_Name.anchor = AnchorPositions.Center;
2、設定position
此方法的基礎是在物件初始化的時候設定物件的rotation或者lookat,然後在Update中更新物件的position
初始化方法:
總之,一個更新rotation一個更新position,個人感覺更新position更好一些,父物件rotation時,子物件跟著rotation會出現抖動的現象,如果使用差值,這會出現rotation延遲的現象,所以更新position更好一些。headShowObj = new GameObject("playerName"); objTrans = headShowObj.transform; objTrans.parent = _controller.trans;// Camera.main.transform; objTrans.localPosition = _controller.trans.localPosition + v; objTrans.localRotation = Quaternion.identity; objTrans.localScale = Vector3.one; objTrans.LookAt(Camera.main.transform.position); m_Name = headShowObj.AddComponent<TextMeshPro>(); m_Name.font = Resources.Load ("UI/Fonts/SIMLI",typeof(TextMeshProFont)) as TextMeshProFont; m_Name.fontSize = 4; m_Name.isOverlay = true; m_Name.alignment = AlignmentTypes.Center; m_Name.anchor = AnchorPositions.Center; lastRotation = m_cameraTransform.rotation; m_Name.transform.rotation = lastRotation;
但是,有一個想法:加入我在初始化時就設定物件的rotation為面向攝像機,而且把它繫結在場景中的父物件,這樣就不用updateposition和rotation了,但是試了下,當父物件rotation時,子物件也跟著rotation,所以,rotation或者position是必須有一個是update的。