簡體   English   中英

由 WASD 控制的 Unity 夾緊旋轉

[英]Unity Clamping Rotation that is controlled by WASD

我想夾住旋轉,旋轉由WASD鍵控制。

我怎樣才能做到這一點? 我嘗試了很多東西,但它不起作用。

    float vertical = Input.GetAxis("Vertical");
    float horizontal = Input.GetAxis("Horizontal");

    transform.Rotate(vertical / 4, horizontal / 4, 0.0f);

您要做的是存儲絕對值,例如

// Adjust these via Inspector
public float minPitch = -45;
public float maxPitch = 45;
public float minYaw = -90;
public float maxYaw = 90;
public Vector2 sensitivity = Vector2.one * 0.25f;

private float pitch;
private float yaw;
private Quaternion originalRotation;

private void Awake ()
{
    originalRotation = transform.rotation;
}

void Update ()
{
    pitch += Input.GetAxis("Vertical") * sensitivity.x;
    yaw += Input.GetAxis("Horizontal") * sensitivity.y;

    pitch = Mathf.Clamp(pitch, minPitch, maxPitch);
    yaw = Mathf.Clamp(yaw, minYaw, maxYaw);

    transform.rotation = originalRotation * Quaternion.Euler(pitch, yaw, 0);
}

使用 Math.Clamp()

float vertical = Input.GetAxis("Vertical");
float horizontal = Input.GetAxis("Horizontal");
float minClamp = -5.0f;
float maxClamp = 5.0f;

transform.Rotate(Math.Clamp(vertical / 4, minClamp, maxClamp),
                 Math.Clamp(horizontal / 4, minClamp, maxClamp));

https://docs.microsoft.com/en-us/dotnet/api/system.math.clamp?view=net-6.0#System_Math_Clamp_System_Single_System_Single_System_Single _

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM