简体   繁体   中英

Unity mouse input on mobile

I am new to Unity and I am making a first-person game. I followed this video https://youtu.be/_QajrabyTJc and when I try on Unity Remote 5 and the camera is not rotating. The code is here:

     public float mouseSensitivity = 100f;

    public Transform playerBody;

    float xRotation = 0f;


    void Update()
    {
        float mouseX = Input.GetAxis("Mouse X") * mouseSensitivity * Time.deltaTime;
        float mouseY = Input.GetAxis("Mouse Y") * mouseSensitivity * Time.deltaTime;



        xRotation -= mouseY;
        xRotation = Mathf.Clamp(xRotation, -90f, 90f);

        transform.localRotation = Quaternion.Euler(xRotation, 0f, 0f);
        playerBody.Rotate(Vector3.up * mouseX);

    }

How can I solve this problem? Or is it only because I am using Unity Remote 5, but not on Android mobile?

For touch input on a mobile device you would rather want to use the Input.touches and do something like eg

// I would use a Vector2 here in order to be able
// to have a different sensitivity for the two axis
public Vector2 mouseSensitivity = Vector2.one * 100f;
public Transform playerBody;

private Vector2 startPos;
private float startRot;
private Quaternion originalBodyRot;

void Update()
{
    if(Input.touchCount == 1)
    {
        var touch = Input.GetTouch(0);

        switch(touch.phase)
        {
            case TouchPhase.Began:
                startPos = touch.position;
                startRot = transform.localEulerAngles.x;
                originalBodyRot = playerBody.rotation;
                break;

            case TouchPhase.Moved:
                var delta = Vector2.Scale(touch.position - startPos, mouseSensitivity);

                var newRot = Mathf.Clamp(startRot - delta.y, -90, 90);
                transform.localEulerAngles = new Vector3 (newRot, 0, 0);

                playerBody.rotation = originalBodyRot * Quaternion.Euler(0, delta.x, 0);            
                break;
        }
    }
}

Note that the touch.position is in pixel space so you might have to adjust your sensitivity.


Note: Typed on smartphone but I hope the idea gets clear

I've also recently added Mouse & Keyboard support to Unity3D. So it works just like it does on PC.

https://assetstore.unity.com/packages/tools/input-management/mobile-input-capture-221017

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM