我創建了一個項目,當我們觸摸它時,一個立方體就會旋轉。當用戶停止觸摸立方體時,我希望立方體返回其原始位置。下面我已經加入旋轉的立方體的源代碼:如何在統一旋轉後將對象恢復到原始位置?
using UnityEngine;
using System.Collections;
[RequireComponent(typeof(MeshRenderer))]
public class dr : MonoBehaviour
{
#region ROTATE
private float _sensitivity = 1f;
private Vector3 _mouseReference;
private Vector3 _mouseOffset;
private Vector3 _rotation = Vector3.zero;
private bool _isRotating;
#endregion
void Update()
{
if(_isRotating)
{
// offset
_mouseOffset = (Input.mousePosition - _mouseReference); // apply rotation
_rotation.y = -(_mouseOffset.x + _mouseOffset.y) * _sensitivity; // rotate
gameObject.transform.Rotate(_rotation); // store new mouse position
_mouseReference = Input.mousePosition;
}
}
void OnMouseDown()
{
// rotating flag
_isRotating = true;
// store mouse position
_mouseReference = Input.mousePosition;
}
void OnMouseUp()
{
// rotating flag
_isRotating = false;
}
}
編輯的代碼: - 使用UnityEngine;使用System.Collections的 ;
[RequireComponent(typeof運算(MeshRenderer))]
公共類PT:MonoBehaviour {
#region ROTATE
private float _sensitivity = 1f;
private Vector3 _mouseReference;
private Vector3 _mouseOffset;
private Vector3 _rotation = Vector3.zero;
private bool _isRotating;
private Quaternion original;
#endregion
void start(){
original = transform.rotation;
}
void Update()
{
if(_isRotating)
{
// offset
_mouseOffset = (Input.mousePosition - _mouseReference); // apply rotation
_rotation.y = -(_mouseOffset.x + _mouseOffset.y) * _sensitivity; // rotate
gameObject.transform.Rotate(_rotation); // store new mouse position
_mouseReference = Input.mousePosition;
}
}
public void OnMouseDown()
{
// rotating flag
_isRotating = true;
// store mouse position
_mouseReference = Input.mousePosition;
}
public void OnMouseUp()
{
// rotating flag
_isRotating = false;
transform.rotation = original;
}
}
「我嘗試轉動沙發的3D模型和迴歸它的起始旋轉。但如果我用這個代碼「每當我停止觸摸沙發,它變成**背面沙發」** 我希望它回到最初的腐爛通貨膨脹。 u can see initally this is how the sofa looks like and if i stopped touching it returns to its backside of sofa. i want it to return to its front side again if i stopped rotation
如果你想讓'Mukesh'回答你的問題,那麼就像個人一樣,你爲什麼要在這裏發帖? –
你想讓它立即回到原來的位置,或者你想讓它旋轉回原來的位置? – Isuka
@aishwariya如果你可以避免使用大寫鎖定,我將不勝感激。沒有目的,它不會幫助你做任何事情。你能否詳細說明你究竟稱爲「原始位置」?你的意思是你的物體的**位置**,或者物體的原始**旋轉**?因爲當我正在閱讀你的問題時,你似乎更多的是在談論你的對象的原始旋轉。 – Isuka