简体   繁体   中英

How can I fix my mouse not rotation the camera on the X axis?

So my problem is with my controllable first person camera, which is currently just a camera with a collider, Character Controller, and this script on it. When I enter the game, the MouseX values change in the insector, but the camera itself appear to be locked, I can only move it up and down. This is just a small amount of the main code, but I think it contains enough to show the problem.

[SerializeField]
private Camera m_Camera;
[SerializeField]
private CharacterController m_CharacterController;

[SerializeField]
private float m_MouseX;
[SerializeField]
private float m_MouseY;

 void Update()
{
    Rotate();
    Movement();
}

private void Rotate()
{
    // Receive mouse input and modifies
    m_MouseX += Input.GetAxis("Mouse X") * m_LookSensitivity;
    m_MouseY += Input.GetAxis("Mouse Y") * m_LookSensitivity;

    // Keep mouseY between -90 and +90
    m_MouseY = Mathf.Clamp(m_MouseY, -90.0f, 90.0f);

    // Rotate the player object around the y-axis
    transform.localRotation = Quaternion.Euler(Vector3.up * m_MouseX);
    // Rotate the camera around the x-axis
    m_Camera.transform.localRotation = Quaternion.Euler(Vector3.left * m_MouseY);
}

You will work better if you rotate by using the transform.Rotate() method instead of modifying the Quaternion, for example:

private void Rotate()
{
    // Receive mouse input and modifies
    m_MouseX += Input.GetAxis("Mouse X") * m_LookSensitivity;
    m_MouseY += Input.GetAxis("Mouse Y") * m_LookSensitivity;

    // Rotate the player object around the y-axis
    transform.Rotate(Vector3.up * m_MouseX);

    // Rotate the camera around the x-axis
    m_Camera.transform.Rotate(Vector3.left * m_MouseY);
}

And if you want to limit the max angle of your camera at (-90, 90) you can accumulate the m_MouseY on another variable, and rotate each way (+/-) only when that variable is inside of the correct inverval, for example:

totalY += m_MouseY;
if (totalY < 90 && m_MouseY > 0)
   m_Camera.transform.Rotate(Vector3.left * m_MouseY);
if (totalY > -90 && m_MouseY < 0)
   m_Camera.transform.Rotate(Vector3.left * m_MouseY);

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