12

In my game I have a camera and I want to have an FPS like rotation attached to this camera.

So if I move my cursor to the left, I want my cam to rotate to the left. If I move my cursor up, then the cam should look up, etc.

I currently have it partially working. I can look left and right, up, and down. The problem occurs when I look down and then move my cursor left and right. It then gives me a "Roll" effect.

See this video to see exactly what I mean: http://www.screencast.com/t/Phedh8H0K13

Obviously when I look down I still want to have a "Yaw" effect instead of a "Roll" effect. Anyone any idea how to do that? This is what I have so far:

// Update is called once per frame
public override void update ()
{
    this.camera.transform.rotation *= 
        Quaternion.AngleAxis( Time.deltaTime * sensitivityRoll * Input.GetAxis("Vertical"), Vector3.forward );

    this.camera.transform.rotation *= 
        Quaternion.AngleAxis( Time.deltaTime * sensitivityYaw * Input.GetAxis("Mouse X"), Vector3.up );

    this.camera.transform.rotation *= 
        Quaternion.AngleAxis( Time.deltaTime * sensitivityPitch * Input.GetAxis("Mouse Y"), Vector3.left );
}

4 Answers 4

19

I just found my answer in this topic:

http://forum.unity3d.com/threads/109250-Looking-with-the-Mouse?highlight=person+camera


The code from that topic:

C# Mono code:

using UnityEngine;
using System.Collections;

/// MouseLook rotates the transform based on the mouse delta.
/// Minimum and Maximum values can be used to constrain the possible rotation

/// To make an FPS style character:
/// - Create a capsule.
/// - Add the MouseLook script to the capsule.
///   -> Set the mouse look to use LookX. (You want to only turn character but not tilt it)
/// - Add FPSInputController script to the capsule
///   -> A CharacterMotor and a CharacterController component will be automatically added.

/// - Create a camera. Make the camera a child of the capsule. Reset it's transform.
/// - Add a MouseLook script to the camera.
///   -> Set the mouse look to use LookY. (You want the camera to tilt up and down like a head. The character already turns.)
[AddComponentMenu("Camera-Control/Mouse Look")]
public class MouseLook : MonoBehaviour {

    public enum RotationAxes { MouseXAndY = 0, MouseX = 1, MouseY = 2 }
    public RotationAxes axes = RotationAxes.MouseXAndY;
    public float sensitivityX = 15F;
    public float sensitivityY = 15F;

    public float minimumX = -360F;
    public float maximumX = 360F;

    public float minimumY = -60F;
    public float maximumY = 60F;

    float rotationY = 0F;

    void Update ()
    {
        if (axes == RotationAxes.MouseXAndY)
        {
            float rotationX = transform.localEulerAngles.y + Input.GetAxis("Mouse X") * sensitivityX;

            rotationY += Input.GetAxis("Mouse Y") * sensitivityY;
            rotationY = Mathf.Clamp (rotationY, minimumY, maximumY);

            transform.localEulerAngles = new Vector3(-rotationY, rotationX, 0);
        }
        else if (axes == RotationAxes.MouseX)
        {
            transform.Rotate(0, Input.GetAxis("Mouse X") * sensitivityX, 0);
        }
        else
        {
            rotationY += Input.GetAxis("Mouse Y") * sensitivityY;
            rotationY = Mathf.Clamp (rotationY, minimumY, maximumY);

            transform.localEulerAngles = new Vector3(-rotationY, transform.localEulerAngles.y, 0);
        }
    }

    void Start ()
    {
    //if(!networkView.isMine)
        //enabled = false;

        // Make the rigid body not change rotation
        //if (rigidbody)
            //rigidbody.freezeRotation = true;
    }
}
Sign up to request clarification or add additional context in comments.

1 Comment

Years late but thanks for the answer, that's exactly what I was looking for!
0

Simple Script, Not Sure it will work with you, might as well give it a try

using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Security.Cryptography;
using System.Threading;
using UnityEngine;

public class mouse_lookat : MonoBehaviour
{
    public float mouseSensitivity = 100f;

    public Transform playerBody;

    float xRotation = 0f;

    // Start is called before the first frame update
    void Start()
    {
        Cursor.lockState = CursorLockMode.Locked;
    }

    // Update is called once per frame
    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);
    }
}

1 Comment

Why using System.Security.Cryptography;??
0
using UnityEngine;

public class CameraRotator : MonoBehaviour
{
    [SerializeField] private Transform _head;
    [SerializeField] private float _sensitivity;
    [SerializeField] private bool _invertVertical;

    private void Update()
    {
        var deltaMouse = new Vector2(Input.GetAxisRaw("Mouse X"), Input.GetAxisRaw("Mouse Y");
        
        Vector2 deltaRotation = deltaMouse * _sensitivity;
        deltaRotation.y *= _invertVertical ? 1.0f : -1.0f;

        float pitchAngle = _head.localEulerAngles.x;
        
        // turns 270 deg into -90, etc
        if (pitchAngle > 180)
            pitchAngle -= 360;

        pitchAngle = Mathf.Clamp(pitchAngle + deltaRotation.y, -90.0f, 90.0f);

        transform.Rotate(Vector3.up, deltaRotation.x);
        _head.localRotation = Quaternion.Euler(pitchAngle, 0.0f, 0.0f);
    }
}

1 Comment

While this code may answer the question, providing additional context regarding why and/or how this code answers the question improves its long-term value.
-1

i created 2 scripts for my FPS project that work flawlessly for my movement (currently havnt added jump mechanics) and it seems like youve overcomplicated alot of things that can be quite simple and straight forward. im also new to coding so please correct me if im wrong heres my code

// this is in the player script which i put on an empty parent object of the camera and player sprite

public class player : MonoBehaviour
{
    [Header("player Movement")]
    [SerializeField] float moveSpeed = 5f;
    [SerializeField] public float mouseSensitivity = 5f;

    
    Rigidbody rigidBody;
   
    // Use this for initialization
    void Start()
    {
        
    }

 void Update()
    {
        Move();
       
    }


    private void Move()
    {
        transform.Translate(Vector3.forward * Input.GetAxis("Vertical") * moveSpeed * Time.deltaTime);
        transform.Translate(Vector3.right * Input.GetAxis("Horizontal") * moveSpeed * Time.deltaTime);
        transform.Rotate(Vector3.up * Input.GetAxis("Mouse X") * mouseSensitivity);
    }

//this is the camera movement script which i put on the camera(will also use this script to add a function to change from 1st person to 3rd person for certain abilities)

{

    player player;
    // Use this for initialization
    void Start()
    {
        player = FindObjectOfType<player>();
    }

    // Update is called once per frame
    void Update()
    {
        MoveView();
    }
    private void MoveView()
    {
        transform.Rotate(Vector3.left * Input.GetAxis("Mouse Y") * player.mouseSensitivity);
    }
}

2 Comments

GetAxis on a mouse axis returns the difference in absolute mouse movement since the last frame. Do not--I REPEAT, DO NOT--multiply GetAxis of a mouse axis by deltaTime, unless you want the speed of the mouse movement to matter more than the distance the mouse traveled. That's really unintuitive in most cases, especially this one!
And, even if you do, you probably mean to be dividing by deltaTime in those cases ( because velocity = delta position / delta time)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.