簡體   English   中英

試圖讓鼠標控制 Unity 中的相機

[英]Trying to get Mouse to control camera in Unity

我正在使用本教程使用鼠標測試 VR 游戲,並且在大多數情況下我都能正常工作,除了每次我切換要移動的軸時它似乎“重置”X 或 Y position . 例如,如果我移動鼠標 x 軸,它會旋轉視圖,但如果我移動 y 軸,x 位置(代碼中的 .localRotation)會回到 0(在原始位置直視前方)。 然后,如果我再次移動 x 軸,y 軸位置將回到零,但 x position 會回到我上次離開的位置。

我覺得不是這段代碼在做,但我會粘貼在這里以防萬一:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.InputSystem;

public class MouseLook : MonoBehaviour
{
    
    public InputActionReference horizontalLook;
    public InputActionReference verticalLook;
    public float lookSpeed = 0.25f;
    public Transform cameraTransform;
    float pitch;
    float yaw;
    
    // Start is called before the first frame update
    void Start()
    {
        Cursor.lockState = CursorLockMode.Locked;
        horizontalLook.action.performed += HandleHorizontalLookChange;
        verticalLook.action.performed += HandleVerticalLookChange;
    }


    void HandleHorizontalLookChange(InputAction.CallbackContext obj)
    {
            yaw += obj.ReadValue<float>();
            transform.localRotation = Quaternion.AngleAxis(yaw * lookSpeed, Vector3.up);
            
    }

    void HandleVerticalLookChange(InputAction.CallbackContext obj)
    {
            pitch += obj.ReadValue<float>();
            transform.localRotation = Quaternion.AngleAxis(pitch * lookSpeed, Vector3.right);
            
    }

}


您根據鼠標 position 或增量的總和將旋轉設置為顯式值(沒有看到輸入資產不清楚,但我假設增量),因此您的旋轉被“重置”為僅由當前軸給出的精確旋轉每次。

解決方案 1 通過將新旋轉乘以當前旋轉的左側,將新旋轉添加到現有旋轉中,例如localRotation = Quaternion.AngleAxis(...) * localRotation;

解決方案2(推薦) 由於四元數不像角度那樣直觀地理解,Unity提供了一個方便的方法 function 在每個Transform上調用Rotate(axis, angle) object => transform.Rotate(<Vector3 as axis>, <your angle value>);

然而,在這兩種方法中,角度值都應該根據鼠標增量計算,而不是絕對屏幕 position 或增量總和。

請務必閱讀本手冊頁上的公共方法部分,以全面了解如何在 Unity 中操作變換: https://docs.unity3d.com/ScriptReference/Transform.html

暫無
暫無

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

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