Jump to content
Unity Insider Forum

Maus Sicht Rotation abstellen ! ? !


w0rks

Recommended Posts

Hallo habe endlich meine Perfekte Kamerasicht (Umsehen) so eingestellt wie ich sie brauche :) Nur was mich persönlich stört ist das sich die Kamera anders rotiert, beim bewegen ! <_< !

Wie und wo kann ich das abstellen wüsste jemand Rat ? Bitte selbst ausprobieren damit man weis was ich meine

LG        w0rks

using UnityEngine;
using UnityEngine.Serialization;

public class FreelookCamera : MonoBehaviour {	
	[Tooltip("Default speed in m/s")]
	public float Speed = 5;
	[FormerlySerializedAs("EnableFastSpeed")]
	[Tooltip("Whether to use the faster speed option while holding the boost key")]
	public bool EnableBoostSpeed = true;
	[FormerlySerializedAs("FastSpeed")]
	[Tooltip("Speed in m/s while holding the boost key")]
	public float BoostSpeed = 10;

	[Tooltip("Hotkey used to boost movement speed")]
	public KeyCode BoostKey = KeyCode.LeftShift;

	[Tooltip("The speed at which your camera rotates when moving the mouse")]
	public float MouseSensitivity = 3;

	[Tooltip("Whether the freelook is initially enabled")]
	public bool IsEnabled = true;		//intern isEnabled bool. The reason we dont use MonoBehaviour's .enabled property is so that we can turn it back on again with the hotkey in Update

	[Tooltip("Whether to lock the cursor while using the freelook camera")]
	public bool LockCursor = true;

	[Tooltip("The hotkey used to enable or disable the freelook camera script")]
	public KeyCode ToggleKey = KeyCode.T;	//hotkey used for enabling or disabling the freelook script

	[Tooltip("Hotkey used to move upwards on the vertical world axis")]
	public KeyCode UpKey = KeyCode.E;

	[Tooltip("Hotkey used to move downwards on the vertical world axis")]
	public KeyCode DownKey = KeyCode.Q;

	private Quaternion originalRotation;
	private float rotationX;
	private float rotationY;

	private Transform myTransform;			//cache of the .tranform property for better performance

	private bool wasUsingKinematic;			//was the (if attached) rigidbody using Kinamtic mode before the freelook was enabled?

	// Use this for initialization
	public void Start () {
		myTransform = transform;
		originalRotation = myTransform.localRotation;

		if(IsEnabled)
			EnableNoClip();
	}

	//called by unity
	public void OnEnable() {
		if(IsEnabled)
			EnableNoClip();
	}

	//called by unity
	public void OnDisable() {
		if(IsEnabled)
			DisableNoClip();
	}
	
	// Update is called once per frame
	public void Update () {
		#region Inputhandling
		//handle enabling/disabling of the component
		if( Input.GetKeyUp (ToggleKey) ) {
			if( IsEnabled ) {
				DisableNoClip();
			}
			else {
				EnableNoClip();
			}
		}

		//lock the cursor if specified to do so in the inspector
		if (LockCursor) {
			Cursor.lockState = CursorLockMode.Locked;
			Cursor.visible = false;
			//Screen.lockCursor = true;	//this was the pre-Unity 5.0 way of locking the cursor
		}

		//Get the speed based on user input
		float currentSpeed = Speed;
		if(EnableBoostSpeed && Input.GetKey(BoostKey)) {
			currentSpeed = BoostSpeed;
		}

		float verticalMovement = 0;
		if (Input.GetKey(UpKey)) {
			verticalMovement += 0.5f;
		}

		if (Input.GetKey(DownKey)) {
			verticalMovement -= 0.5f;
		}
		#endregion

		if(!IsEnabled) return;

		#region MouseLook
		// Read the mouse input axis
		rotationX += Input.GetAxis("Mouse X") * MouseSensitivity;
		rotationY += Input.GetAxis("Mouse Y") * MouseSensitivity;

		rotationY = Mathf.Clamp(rotationY, -90f, 90f);

		Quaternion xQuaternion = Quaternion.AngleAxis(rotationX, Vector3.up);
		Quaternion yQuaternion = Quaternion.AngleAxis(rotationY, -Vector3.right);

		myTransform.rotation = originalRotation * xQuaternion * yQuaternion;
		#endregion

		#region Movement
		//make speed frame-independant
		currentSpeed *= Time.deltaTime;

		verticalMovement = verticalMovement * currentSpeed;

		//Read from Unity input and apply speed
		float currentForwardSpeed = Input.GetAxis ("Vertical") * currentSpeed;
		float currentSidewardSpeed = Input.GetAxis("Horizontal") * currentSpeed;

		Vector3 fwd = myTransform.forward;
		Vector3 left = myTransform.right;
		myTransform.position = myTransform.position + ((fwd * currentForwardSpeed) + (left * currentSidewardSpeed) + Vector3.up * verticalMovement);
		#endregion
	}
	
	/// <summary>
	/// Enables the freelook camera, disabling or configuring any other component that might be present and interfere with the freelook camera
	/// </summary>
	private void EnableNoClip() {
		//Integration with the Unity's standard assets' character motor. If you are not using this, you can delete the following 4 lines
		Behaviour motor = gameObject.GetComponent("CharacterMotor") as MonoBehaviour;
		if (motor != null) {
			motor.enabled = false;
		}

		//enables isKinematic on the rigidbody, if present. (this saves the previous state, to not interfere with your own game logic)
		Rigidbody body = gameObject.GetComponent<Rigidbody>();
		if (body != null) {
			wasUsingKinematic = body.isKinematic;
			if (!body.isKinematic) {
				body.isKinematic = true;
			}
		}
		
		IsEnabled = true;
	}
	
	/// <summary>
	/// Disables the freelook camera, enabling or configuring any other component that might be present and interfere with the freelook camera
	/// </summary>
	private void DisableNoClip() {
		//Integration with the Unity's standard assets' character motor. If you are not using this, you can delete the following 4 lines
		Behaviour motor = gameObject.GetComponent("CharacterMotor") as MonoBehaviour;
		if(motor != null) {
			motor.enabled = true;
		}

		//disables isKinematic on the rigidbody if it was before, if present.
		Rigidbody body = gameObject.GetComponent<Rigidbody>();
		if(body != null) {
			if (!body.isKinematic) return;		//the body isKinematic was set to false by something for some reason, no need to force the saved value

			body.isKinematic = wasUsingKinematic;
		}
		
		IsEnabled = false;
	}
}

 

Link zu diesem Kommentar
Auf anderen Seiten teilen

Hab die Mausrotation noch einmal komplett umgebaut:
Die Kamera wird nun immer horizontal aufgerichtet und damit kann die Kamera nicht mehr auf dem Kopf stehen und sie kommt auch nicht in "seltsame" Schräglagen. So ganz perfekt ist es nicht, wie gesagt ich würde das vorherige von mir gepostete Skript verwenden, da waren diese Problem bereits gelöst.
Bei bestimmten Lagen um Raum kommt es zu einer "plötzlichen" Neuorientierung der Kamera, leider lässt sich das ohne viel Aufwand nicht beheben. Diese entsteht durch das "horizontale Aufrichten" der Kamera. Man könnte dieses Problem beheben, indem man bestimmte Winkel der Kamera verbietet (extremer Winkel in World-Y Achse). Wenn gewünscht kann ich das ggf. noch einbauen.

using UnityEngine;
using UnityEngine.Serialization;

public class FreelookCamera : MonoBehaviour
{
    private Transform target;
    private float distance = 5.0f;

    [Tooltip("Default speed in m/s")]
    public float Speed = 5;
    [FormerlySerializedAs("EnableFastSpeed")]
    [Tooltip("Whether to use the faster speed option while holding the boost key")]
    public bool EnableBoostSpeed = true;
    [FormerlySerializedAs("FastSpeed")]
    [Tooltip("Speed in m/s while holding the boost key")]
    public float BoostSpeed = 10;

    [Tooltip("Hotkey used to boost movement speed")]
    public KeyCode BoostKey = KeyCode.LeftShift;

    [Tooltip("The speed at which your camera rotates when moving the mouse")]
    public float MouseSensitivity = 3;
    public int yMinLimit = -80;
    public int yMaxLimit = 80;
    public int MouseRotationSensitivity = 1;

    [Tooltip("Whether the freelook is initially enabled")]
    public bool IsEnabled = true;       //intern isEnabled bool. The reason we dont use MonoBehaviour's .enabled property is so that we can turn it back on again with the hotkey in Update

    [Tooltip("Whether to lock the cursor while using the freelook camera")]
    public bool LockCursor = true;

    [Tooltip("The hotkey used to enable or disable the freelook camera script")]
    public KeyCode ToggleKey = KeyCode.T;   //hotkey used for enabling or disabling the freelook script

    [Tooltip("Hotkey used to move upwards on the vertical world axis")]
    public KeyCode UpKey = KeyCode.E;

    [Tooltip("Hotkey used to move downwards on the vertical world axis")]
    public KeyCode DownKey = KeyCode.Q;

    private Quaternion originalRotation;
    private float rotationX;
    private float rotationY;
    private float xDeg = 0.0f;
    private float yDeg = 0.0f;
    private Quaternion currentRotation;
    private Quaternion desiredRotation;
    private Quaternion rotation;

    private Transform myTransform;          //cache of the .tranform property for better performance

    private bool wasUsingKinematic;         //was the (if attached) rigidbody using Kinamtic mode before the freelook was enabled?

    // Use this for initialization
    public void Start()
    {
        //If there is no target, create a temporary target at 'distance' from the cameras current viewpoint
        if (!target)
        {
            GameObject go = new GameObject("Cam Target");
            go.transform.position = transform.position + (transform.forward * distance);
            target = go.transform;
        }

        myTransform = transform;
        originalRotation = myTransform.localRotation;

        if (IsEnabled)
            EnableNoClip();

        xDeg = Vector3.Angle(Vector3.right, transform.right);
        yDeg = Vector3.Angle(Vector3.up, transform.up);
        currentRotation = transform.rotation;
        desiredRotation = transform.rotation;
    }

    //called by unity
    public void OnEnable()
    {
        if (IsEnabled)
            EnableNoClip();
    }

    //called by unity
    public void OnDisable()
    {
        if (IsEnabled)
            DisableNoClip();
    }

    // Update is called once per frame
    public void Update()
    {
        #region Inputhandling
        //handle enabling/disabling of the component
        if (Input.GetKeyUp(ToggleKey))
        {
            if (IsEnabled)
            {
                DisableNoClip();
            }
            else
            {
                EnableNoClip();
            }
        }

        //lock the cursor if specified to do so in the inspector
        if (LockCursor)
        {
            Cursor.lockState = CursorLockMode.Locked;
            Cursor.visible = false;
            //Screen.lockCursor = true;	//this was the pre-Unity 5.0 way of locking the cursor
        }

        //Get the speed based on user input
        float currentSpeed = Speed;
        if (EnableBoostSpeed && Input.GetKey(BoostKey))
        {
            currentSpeed = BoostSpeed;
        }

        float verticalMovement = 0;
        if (Input.GetKey(UpKey))
        {
            verticalMovement += 0.5f;
        }

        if (Input.GetKey(DownKey))
        {
            verticalMovement -= 0.5f;
        }
        #endregion

        if (!IsEnabled) return;

        #region MouseLook

        // Read the mouse input axis
        /*
        rotationX += Input.GetAxis("Mouse X") * MouseSensitivity;
        rotationY += Input.GetAxis("Mouse Y") * MouseSensitivity;

        rotationY = Mathf.Clamp(rotationY, -90f, 90f);

        Quaternion xQuaternion = Quaternion.AngleAxis(rotationX, Vector3.up);
        Quaternion yQuaternion = Quaternion.AngleAxis(rotationY, -Vector3.right);

        myTransform.rotation = originalRotation * xQuaternion * yQuaternion;
        */

        xDeg = Input.GetAxis("Mouse X") * MouseSensitivity * 5;
        yDeg = Input.GetAxis("Mouse Y") * MouseSensitivity * 5;

        ////////OrbitAngle

        //Clamp the vertical axis for the orbit
        //yDeg = ClampAngle(yDeg, yMinLimit, yMaxLimit);
        // set camera rotation 
        //desiredRotation = Quaternion.Euler(yDeg, xDeg, 0);
        target.position = transform.position + (transform.forward * distance);
        float upCorrect = Vector3.Dot(this.transform.forward, Vector3.up);        
        if (Mathf.Abs(upCorrect) < 0.9f) transform.LookAt(target, Vector3.up);
        currentRotation = transform.rotation;
        //transform.LookAt(target, Vector3.up);
        transform.Rotate(new Vector3(-yDeg, xDeg, 0), Space.Self);

        desiredRotation = transform.rotation;

        rotation = Quaternion.Lerp(currentRotation, desiredRotation, Time.deltaTime * MouseRotationSensitivity*10);
        transform.rotation = rotation;

        #endregion

        #region Movement
        //make speed frame-independant
        currentSpeed *= Time.deltaTime;

        verticalMovement = verticalMovement * currentSpeed;

        //Read from Unity input and apply speed
        float currentForwardSpeed = Input.GetAxis("Vertical") * currentSpeed;
        float currentSidewardSpeed = Input.GetAxis("Horizontal") * currentSpeed;

        Vector3 fwd = myTransform.forward;
        Vector3 left = myTransform.right;
        myTransform.position = myTransform.position + ((fwd * currentForwardSpeed) + (left * currentSidewardSpeed) + Vector3.up * verticalMovement);
        #endregion
    }

    /// <summary>
    /// Enables the freelook camera, disabling or configuring any other component that might be present and interfere with the freelook camera
    /// </summary>
    private void EnableNoClip()
    {
        //Integration with the Unity's standard assets' character motor. If you are not using this, you can delete the following 4 lines
        Behaviour motor = gameObject.GetComponent("CharacterMotor") as MonoBehaviour;
        if (motor != null)
        {
            motor.enabled = false;
        }

        //enables isKinematic on the rigidbody, if present. (this saves the previous state, to not interfere with your own game logic)
        Rigidbody body = gameObject.GetComponent<Rigidbody>();
        if (body != null)
        {
            wasUsingKinematic = body.isKinematic;
            if (!body.isKinematic)
            {
                body.isKinematic = true;
            }
        }

        IsEnabled = true;
    }

    /// <summary>
    /// Disables the freelook camera, enabling or configuring any other component that might be present and interfere with the freelook camera
    /// </summary>
    private void DisableNoClip()
    {
        //Integration with the Unity's standard assets' character motor. If you are not using this, you can delete the following 4 lines
        Behaviour motor = gameObject.GetComponent("CharacterMotor") as MonoBehaviour;
        if (motor != null)
        {
            motor.enabled = true;
        }

        //disables isKinematic on the rigidbody if it was before, if present.
        Rigidbody body = gameObject.GetComponent<Rigidbody>();
        if (body != null)
        {
            if (!body.isKinematic) return;      //the body isKinematic was set to false by something for some reason, no need to force the saved value

            body.isKinematic = wasUsingKinematic;
        }

        IsEnabled = false;
    }

    private static float ClampAngle(float angle, float min, float max)
    {
        if (angle < -360)
            angle += 360;
        if (angle > 360)
            angle -= 360;
        return Mathf.Clamp(angle, min, max);
    }
}

 

Link zu diesem Kommentar
Auf anderen Seiten teilen

Hab das "Clamping" eingebaut. Die Kamera lässt sich nun nicht mehr "überdrehen":
 

using UnityEngine;
using UnityEngine.Serialization;

public class FreelookCamera : MonoBehaviour
{
    private Transform target;
    private float distance = 5.0f;

    [Tooltip("Default speed in m/s")]
    public float Speed = 5;
    [FormerlySerializedAs("EnableFastSpeed")]
    [Tooltip("Whether to use the faster speed option while holding the boost key")]
    public bool EnableBoostSpeed = true;
    [FormerlySerializedAs("FastSpeed")]
    [Tooltip("Speed in m/s while holding the boost key")]
    public float BoostSpeed = 10;

    [Tooltip("Hotkey used to boost movement speed")]
    public KeyCode BoostKey = KeyCode.LeftShift;

    [Tooltip("The speed at which your camera rotates when moving the mouse")]
    public float MouseSensitivity = 3;
    public int yMinLimit = -80;
    public int yMaxLimit = 80;
    public int MouseRotationSensitivity = 1;

    [Tooltip("Whether the freelook is initially enabled")]
    public bool IsEnabled = true;       //intern isEnabled bool. The reason we dont use MonoBehaviour's .enabled property is so that we can turn it back on again with the hotkey in Update

    [Tooltip("Whether to lock the cursor while using the freelook camera")]
    public bool LockCursor = true;

    [Tooltip("The hotkey used to enable or disable the freelook camera script")]
    public KeyCode ToggleKey = KeyCode.T;   //hotkey used for enabling or disabling the freelook script

    [Tooltip("Hotkey used to move upwards on the vertical world axis")]
    public KeyCode UpKey = KeyCode.E;

    [Tooltip("Hotkey used to move downwards on the vertical world axis")]
    public KeyCode DownKey = KeyCode.Q;

    private Quaternion originalRotation;
    private float rotationX;
    private float rotationY;
    private float xDeg = 0.0f;
    private float yDeg = 0.0f;
    private Quaternion currentRotation;
    private Quaternion desiredRotation;
    private Quaternion rotation;

    private Transform myTransform;          //cache of the .tranform property for better performance

    private bool wasUsingKinematic;         //was the (if attached) rigidbody using Kinamtic mode before the freelook was enabled?

    // Use this for initialization
    public void Start()
    {
        //If there is no target, create a temporary target at 'distance' from the cameras current viewpoint
        if (!target)
        {
            GameObject go = new GameObject("Cam Target");
            go.transform.position = transform.position + (transform.forward * distance);
            target = go.transform;
        }

        myTransform = transform;
        originalRotation = myTransform.localRotation;

        if (IsEnabled)
            EnableNoClip();

        xDeg = Vector3.Angle(Vector3.right, transform.right);
        yDeg = Vector3.Angle(Vector3.up, transform.up);
        currentRotation = transform.rotation;
        desiredRotation = transform.rotation;
    }

    //called by unity
    public void OnEnable()
    {
        if (IsEnabled)
            EnableNoClip();
    }

    //called by unity
    public void OnDisable()
    {
        if (IsEnabled)
            DisableNoClip();
    }

    // Update is called once per frame
    public void Update()
    {
        #region Inputhandling
        //handle enabling/disabling of the component
        if (Input.GetKeyUp(ToggleKey))
        {
            if (IsEnabled)
            {
                DisableNoClip();
            }
            else
            {
                EnableNoClip();
            }
        }

        //lock the cursor if specified to do so in the inspector
        if (LockCursor)
        {
            Cursor.lockState = CursorLockMode.Locked;
            Cursor.visible = false;
            //Screen.lockCursor = true;	//this was the pre-Unity 5.0 way of locking the cursor
        }

        //Get the speed based on user input
        float currentSpeed = Speed;
        if (EnableBoostSpeed && Input.GetKey(BoostKey))
        {
            currentSpeed = BoostSpeed;
        }

        float verticalMovement = 0;
        if (Input.GetKey(UpKey))
        {
            verticalMovement += 0.5f;
        }

        if (Input.GetKey(DownKey))
        {
            verticalMovement -= 0.5f;
        }
        #endregion

        if (!IsEnabled) return;

        #region MouseLook

        // Read the mouse input axis
        /*
        rotationX += Input.GetAxis("Mouse X") * MouseSensitivity;
        rotationY += Input.GetAxis("Mouse Y") * MouseSensitivity;

        rotationY = Mathf.Clamp(rotationY, -90f, 90f);

        Quaternion xQuaternion = Quaternion.AngleAxis(rotationX, Vector3.up);
        Quaternion yQuaternion = Quaternion.AngleAxis(rotationY, -Vector3.right);

        myTransform.rotation = originalRotation * xQuaternion * yQuaternion;
        */

        xDeg = Input.GetAxis("Mouse X") * MouseSensitivity * 5;
        yDeg = Input.GetAxis("Mouse Y") * MouseSensitivity * 5;

        ////////OrbitAngle

        //Clamp the vertical axis for the orbit
        //yDeg = ClampAngle(yDeg, yMinLimit, yMaxLimit);
        // set camera rotation 
        //desiredRotation = Quaternion.Euler(yDeg, xDeg, 0);
        target.position = transform.position + (transform.forward * distance);
        float upCorrect = Vector3.Dot(this.transform.forward, Vector3.up);
        if ((upCorrect > -0.9f || yDeg > 0) && (upCorrect < 0.9f || yDeg < 0))
        {
            transform.LookAt(target, Vector3.up);
            currentRotation = transform.rotation;
            transform.Rotate(new Vector3(-yDeg, xDeg, 0), Space.Self);
            desiredRotation = transform.rotation;
        } else
        {
            transform.LookAt(target, Vector3.up);
            currentRotation = transform.rotation;
            transform.Rotate(new Vector3(0, xDeg, 0), Space.Self);
            desiredRotation = transform.rotation;
        }

        rotation = Quaternion.Lerp(currentRotation, desiredRotation, Time.deltaTime * MouseRotationSensitivity * 10);
        transform.rotation = rotation;

        #endregion

        #region Movement
        //make speed frame-independant
        currentSpeed *= Time.deltaTime;

        verticalMovement = verticalMovement * currentSpeed;

        //Read from Unity input and apply speed
        float currentForwardSpeed = Input.GetAxis("Vertical") * currentSpeed;
        float currentSidewardSpeed = Input.GetAxis("Horizontal") * currentSpeed;

        Vector3 fwd = myTransform.forward;
        Vector3 left = myTransform.right;
        myTransform.position = myTransform.position + ((fwd * currentForwardSpeed) + (left * currentSidewardSpeed) + Vector3.up * verticalMovement);
        #endregion
    }

    /// <summary>
    /// Enables the freelook camera, disabling or configuring any other component that might be present and interfere with the freelook camera
    /// </summary>
    private void EnableNoClip()
    {
        //Integration with the Unity's standard assets' character motor. If you are not using this, you can delete the following 4 lines
        Behaviour motor = gameObject.GetComponent("CharacterMotor") as MonoBehaviour;
        if (motor != null)
        {
            motor.enabled = false;
        }

        //enables isKinematic on the rigidbody, if present. (this saves the previous state, to not interfere with your own game logic)
        Rigidbody body = gameObject.GetComponent<Rigidbody>();
        if (body != null)
        {
            wasUsingKinematic = body.isKinematic;
            if (!body.isKinematic)
            {
                body.isKinematic = true;
            }
        }

        IsEnabled = true;
    }

    /// <summary>
    /// Disables the freelook camera, enabling or configuring any other component that might be present and interfere with the freelook camera
    /// </summary>
    private void DisableNoClip()
    {
        //Integration with the Unity's standard assets' character motor. If you are not using this, you can delete the following 4 lines
        Behaviour motor = gameObject.GetComponent("CharacterMotor") as MonoBehaviour;
        if (motor != null)
        {
            motor.enabled = true;
        }

        //disables isKinematic on the rigidbody if it was before, if present.
        Rigidbody body = gameObject.GetComponent<Rigidbody>();
        if (body != null)
        {
            if (!body.isKinematic) return;      //the body isKinematic was set to false by something for some reason, no need to force the saved value

            body.isKinematic = wasUsingKinematic;
        }

        IsEnabled = false;
    }

    private static float ClampAngle(float angle, float min, float max)
    {
        if (angle < -360)
            angle += 360;
        if (angle > 360)
            angle -= 360;
        return Mathf.Clamp(angle, min, max);
    }
}

 

Link zu diesem Kommentar
Auf anderen Seiten teilen

Archiviert

Dieses Thema ist jetzt archiviert und für weitere Antworten gesperrt.

×
×
  • Neu erstellen...