Last active
November 25, 2017 13:02
-
-
Save kilj/0773928b7b8f4206a3e46d6cac273e47 to your computer and use it in GitHub Desktop.
Unity mouselook + WASD + camera.
This file contains 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
// Based on work of FatiguedArtist from https://forum.unity.com/threads/a-free-simple-smooth-mouselook.73117/ | |
// Added simple WASD controlling, which can be enabled by pressing right mouse button. | |
// Deleted comments and some fields. | |
using UnityEngine; | |
public class WASDMoving : MonoBehaviour | |
{ | |
public Vector2 clampInDegrees = new Vector2(360, 180); | |
public Vector2 sensitivity = new Vector2(2, 2); | |
public Vector2 smoothing = new Vector2(3, 3); | |
private Vector2 mouseAbsolute; | |
private Vector2 smoothMouse; | |
private Vector2 targetDirection; | |
private void Start() | |
{ | |
targetDirection = transform.localRotation.eulerAngles; | |
} | |
private void Update() | |
{ | |
if (!Input.GetMouseButton(1)) return; | |
// Mouse look | |
var targetOrientation = Quaternion.Euler(targetDirection); | |
var mouseDelta = new Vector2(Input.GetAxisRaw("Mouse X"), Input.GetAxisRaw("Mouse Y")); | |
mouseDelta = Vector2.Scale(mouseDelta, new Vector2(sensitivity.x * smoothing.x, sensitivity.y * smoothing.y)); | |
smoothMouse.x = Mathf.Lerp(smoothMouse.x, mouseDelta.x, 1f / smoothing.x); | |
smoothMouse.y = Mathf.Lerp(smoothMouse.y, mouseDelta.y, 1f / smoothing.y); | |
mouseAbsolute += smoothMouse; | |
if (clampInDegrees.x < 360) | |
mouseAbsolute.x = Mathf.Clamp(mouseAbsolute.x, -clampInDegrees.x * 0.5f, clampInDegrees.x * 0.5f); | |
if (clampInDegrees.y < 360) | |
mouseAbsolute.y = Mathf.Clamp(mouseAbsolute.y, -clampInDegrees.y * 0.5f, clampInDegrees.y * 0.5f); | |
transform.localRotation = Quaternion.AngleAxis(-mouseAbsolute.y, targetOrientation * Vector3.right) * targetOrientation; | |
var yRotation = Quaternion.AngleAxis(mouseAbsolute.x, transform.InverseTransformDirection(Vector3.up)); | |
transform.localRotation *= yRotation; | |
// WASD | |
var isShiftPressed = Input.GetKey(KeyCode.LeftShift); | |
var x = Input.GetAxis("Horizontal") * Time.deltaTime * 3f; | |
var z = Input.GetAxis("Vertical") * Time.deltaTime * 3f; | |
transform.Translate(isShiftPressed ? x * 3 : x, 0, isShiftPressed ? z * 3 : z); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment