Last active
March 28, 2018 08:05
-
-
Save wizcas/275ec86ffbc7888cca97b04b497226ea to your computer and use it in GitHub Desktop.
Free-look Camera Controller
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
using System.Collections; | |
using System.Collections.Generic; | |
using UnityEngine; | |
using Cheers; | |
public class FreeLook : MonoBehaviour | |
{ | |
public float mouseSpeed = 10f; | |
public float minYaw = -40; | |
public float maxYaw = 40; | |
public float minPitch = 0; | |
public float maxPitch = 20; | |
public float turnSpeed = 10; | |
[Header("Toggle")] | |
public bool mouseLook; | |
float _xAngle = 0F; | |
float _yAngle = 0F; | |
Quaternion _origRot; | |
Quaternion _toRot; | |
private void Start() | |
{ | |
_origRot = _toRot = transform.localRotation; | |
} | |
private void Update() | |
{ | |
if (mouseLook) | |
{ | |
TurnHeadDelta(Input.GetAxis("Mouse X") * mouseSpeed, Input.GetAxis("Mouse Y") * mouseSpeed); | |
} | |
UpdateLookDir(); | |
} | |
void TurnHeadTo(Vector2 toAngles) | |
{ | |
var deltaX = toAngles.x - _xAngle; | |
var deltaY = toAngles.y - _yAngle; | |
TurnHeadDelta(deltaX, deltaY); | |
} | |
void TurnHeadDelta(float deltaHorizontal, float deltaVertical) | |
{ | |
_xAngle += deltaHorizontal; | |
_yAngle += deltaVertical; | |
_xAngle = ClampAngle(_xAngle, minYaw, maxYaw); | |
_yAngle = ClampAngle(_yAngle, minPitch, maxPitch); | |
Quaternion xRot = Quaternion.AngleAxis(_xAngle, Vector3.up); | |
Quaternion yRot = Quaternion.AngleAxis(_yAngle, -Vector3.right); | |
_toRot = xRot * yRot * _origRot; | |
} | |
void UpdateLookDir() | |
{ | |
if (Quaternion.Angle(transform.localRotation, _toRot) >= .01f) | |
{ | |
transform.localRotation = Quaternion.RotateTowards( | |
transform.localRotation, | |
_toRot, | |
turnSpeed); | |
} | |
else | |
{ | |
transform.localRotation = _toRot; | |
} | |
} | |
public static float ClampAngle(float angle, float min, float max) | |
{ | |
if (angle < -360F) | |
angle += 360F; | |
if (angle > 360F) | |
angle -= 360F; | |
return Mathf.Clamp(angle, min, max); | |
} | |
public void RestToOriginal() | |
{ | |
TurnHeadTo(Vector2.zero); | |
} | |
#region Helper | |
[Header("Quick Dirs")] | |
public Vector2 WestAngles = new Vector2(-40, 15); | |
public Vector2 EastAngles = new Vector2(40, 15); | |
public Vector2 NorthAngles = new Vector2(0, 20); | |
void LookAtWestSeat() | |
{ | |
TurnHeadTo(WestAngles); | |
} | |
void LookAtEastSeat() | |
{ | |
TurnHeadTo(EastAngles); | |
} | |
void LookAtNorthSeat() | |
{ | |
TurnHeadTo(NorthAngles); | |
} | |
#endregion | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment