Last active
August 31, 2019 14:58
-
-
Save Kzumueller/a7568ecbc1eb55d95c62d3883f2f3fbd to your computer and use it in GitHub Desktop.
Controls for a camera with 5 degrees of freedom in Unity3D
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using UnityEngine; | |
/** | |
* Controls for a free-roaming camera with 5 degrees of freedom (rotation around z is disabled) | |
* Uses default input axes with the scroll wheel for moving up and down - Shift/Control is also a nice idea | |
*/ | |
public class CameraMovement : MonoBehaviour | |
{ | |
/** absolute rotations kept separately from the attached GameObject */ | |
private float rotationX = 0f; | |
private float rotationY = 0f; | |
/** multiplier for camera rotations */ | |
public float cameraSensitivity = 5f; | |
/** multiplier for strafing and moving forward/backwards */ | |
public float movementSpeedXZ = 1f; | |
/** separate multiplier for moving vertically since the scroll wheel can be awfully slow */ | |
public float movementSpeedY = 5f; | |
/** rotates and translates the GameObject */ | |
void Update() { | |
var newRotationX = (rotationX - Input.GetAxis("Mouse Y") * cameraSensitivity) % 360; | |
// keeping the angle around the x-axis between -90 and 90 degrees | |
rotationX = Mathf.Max(Mathf.Min(newRotationX, 90f), -90f); | |
rotationY = (rotationY + Input.GetAxis("Mouse X") * cameraSensitivity) % 360; | |
// setting rotation directly to avoid tilting around the z-axis | |
transform.rotation = Quaternion.Euler(rotationX, rotationY, 0); | |
transform.Translate( | |
Input.GetAxis("Vertical") * movementSpeedXZ * (transform.worldToLocalMatrix * transform.forward) | |
+ Input.GetAxis("Horizontal") * movementSpeedXZ * (transform.worldToLocalMatrix * transform.right) | |
+ Input.GetAxis("Mouse ScrollWheel") * movementSpeedY * (transform.worldToLocalMatrix * transform.up) | |
); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment