简体   繁体   中英

unity rotate object on x-axis when moving mouse up / down

I want to rotate a object on the x-axis when I move the mouse up or down (increase the x-rotation when moving mouse up, decrease when moving mouse down).

But I don't know how to do this.

I tried this script:

public float mouseSensitivity = 100.0F;
public float clampAngle = 80.0F;

float rotX = 0.0F, rotY = 0.0F;

void Update()
{
    // Mouse Look
    float mouseX = Input.GetAxis("Mouse X");
    float mouseY = Input.GetAxis("Mouse Y");

    rotX += mouseY * mouseSensitivity * Time.deltaTime;
    rotY += mouseX * mouseSensitivity * Time.deltaTime;

    rotX = Mathf.Clamp(rotX, -clampAngle, clampAngle);

    Quaternion localRotation = Quaternion.Euler(rotX, 0, 0.0F);
    transform.rotation = localRotation;
}

But this controls also rotation on the y axis. I also have rotation on the y-axis, but they are controlled via keyboard input:

if (Input.GetKey(KeyCode.W) && !Input.GetKey(KeyCode.S))
    transform.Translate(Vector3.forward * Time.deltaTime * moveSpeed);
else if (Input.GetKey(KeyCode.S) && !Input.GetKey(KeyCode.W))
    transform.Translate(Vector3.forward * Time.deltaTime * -moveSpeed);

if (Input.GetKey(KeyCode.A) && !Input.GetKey(KeyCode.D))
    transform.Rotate(Vector3.up * Time.deltaTime * -rotateSpeed, Space.World);
else if (Input.GetKey(KeyCode.D) && !Input.GetKey(KeyCode.A))
    transform.Rotate(Vector3.up * Time.deltaTime * rotateSpeed, Space.World);

and I want the mouse up/down only control the rotation on the x-axis.

If someone can help me, that would be great!

void Update() {

 // Mouse Look 

float mouseX = Input.GetAxis("Mouse X");

float mouseY = Input.GetAxis("Mouse Y");

rotX = mouseY * mouseSensitivity;

rotY = mouseX * mouseSensitivity;

transform.rotation *= Quaternion.Euler(rotX, 0, 0.0f);

}

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