[英]How to rotate 3d object by swiping?
我的場景中有一個水平圓柱體,我想通過左右滑動來旋轉它(在z軸上),我創建了這個腳本,但是它沒有用,請您告訴我問題出在哪里?
public class SwipeControl : MonoBehaviour {
public Transform Cylinder;
void Update()
{
if (Input.touchCount == 1)
{
// GET TOUCH 0
Touch touch0 = Input.GetTouch(0);
// APPLY ROTATION
if (touch0.phase == TouchPhase.Moved)
{
Cylinder.transform.Rotate(0f, 0f, touch0.deltaPosition.x);
}
}
}
}
不要使用Cylinder
作為變量的名稱,因為它是Unity原語的類名:
https://docs.unity3d.com/ScriptReference/PrimitiveType.Cylinder.html
編輯:正如Stijn所說,代碼可以工作,但是將變量與某些類名完全相等是一種不好的做法。
因此,例如,如果將變量的名稱替換為myCylinder
,則代碼現在如下所示:
public class SwipeControl : MonoBehaviour {
public Transform myCylinder;
void Update()
{
if (Input.touchCount == 1)
{
// GET TOUCH 0
Touch touch0 = Input.GetTouch(0);
// APPLY ROTATION
if (touch0.phase == TouchPhase.Moved)
{
myCylinder.transform.Rotate(Vector3.Right, touch0.deltaPosition.x, Space.World);
}
}
}
}
告訴我是否可以更改名稱並從“編輯器”中設置引用有效。
編輯:注意Rotate
功能,如果要輸入3個參數,則它們應該是Rotate(Vector3 axis, float angle, Space relativeTo = Space.Self);
因此,您當前正在應用0度差異!
這是Rotate
函數以及所有可以使用的不同構造函數和重載方法的文檔鏈接:
https://docs.unity3d.com/ScriptReference/Transform.Rotate.html
測試此筆划時是否使用觸摸屏或鼠標?
觸摸僅適用於觸摸,不適用於鼠標單擊。
您是否嘗試過使用鼠標輸入來移動它?
public class SwipeControl : MonoBehaviour {
public Transform cylinder;
private float sensitivity = 10f;
void Update()
{
if (Input.GetMouseButton(0))
{
float xAxis = Input.GetAxis("Mouse X");
cylinder.Rotate(0, -xAxis * sensitivity * Time.deltaTime, 0);
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.