[英]How to lock z rotation in Unity3D?
我試圖讓移動控件統一工作,但是當我嘗試向左和向右看時,相機會稍微傾斜,所以我想鎖定 z 旋轉,但我不能。
using UnityEngine;
using DitzeGames.MobileJoystick;
namespace DitzeGames.MobileJoystick.Example
{
public class BoxMover : MonoBehaviour {
public Transform transform;
protected Joystick Joystick;
protected Button Button;
protected TouchField TouchField;
// Use this for initialization
void Awake ()
{
Joystick = FindObjectOfType<Joystick>();
Button = FindObjectOfType<Button>();
TouchField = FindObjectOfType<TouchField>();
}
// Update is called once per frame
void FixedUpdate () {
transform.position = new Vector3(transform.position.x +
Joystick.AxisNormalized.x * Time.deltaTime * 3f, Button.Pressed ? 2 : 1,
transform.position.z + Joystick.AxisNormalized.y * Time.deltaTime * 3f);
transform.Rotate(Vector3.up, TouchField.TouchDist.x);
transform.Rotate(Vector3.left, TouchField.TouchDist.y);
}
}}
誰能幫我 ? 謝謝 !
只需添加一個剛體並鎖定 z 旋轉,然后關閉重力。 你可以將它的碰撞器設置為觸發,這樣它就不會撞到任何東西。
這是我為完全鎖定相機旋轉而不使用剛體而編寫的解決方案。 只需創建此腳本並將其添加到您的相機(或您想鎖定的任何內容)。
public class RotationLock : MonoBehaviour
{
private Quaternion lockedRotation;
void Start() { lockedRotation = transform.rotation; }
void Update() { transform.rotation = lockedRotation; }
}
這是另一個版本,可讓您選擇要鎖定的軸。 我為一個 3D 手機游戲編寫了它,用戶可以通過滑動來旋轉他們的視圖。
public class RotationLock : MonoBehaviour
{
public bool lockX, lockY, lockZ;
private Vector3 startRotation;
void Start() { startRotation = transform.rotation.eulerAngles; }
void LateUpdate()
{
Vector3 newRotation = transform.rotation.eulerAngles;
transform.rotation = Quaternion.Euler(
lockX ? startRotation.x : newRotation.x,
lockY ? startRotation.y : newRotation.y,
lockZ ? startRotation.z : newRotation.z
);
}
}
可能有更有效的解決方案,但這些都是在緊要關頭工作,不會涉及物理系統!
嘗試添加將在每幀結束時重置相機傾斜度的代碼。
var rot = transform.rotation;
Camera.main.transform.rotation = new Quaternion(rot .x,rot .y, 0, rot .w);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.