Skip to content

Instantly share code, notes, and snippets.

@rhedgeco
Created February 20, 2022 21:14
Show Gist options
  • Save rhedgeco/0bbaed2c5eec7b1c316c064e4954ce2f to your computer and use it in GitHub Desktop.
Save rhedgeco/0bbaed2c5eec7b1c316c064e4954ce2f to your computer and use it in GitHub Desktop.
A simple free camera script for Unity3d
using UnityEngine;
public class SimpleFreeCamera : MonoBehaviour
{
[SerializeField] private float normalSpeed = 10f;
[SerializeField] private float shiftSpeed = 15f;
[SerializeField] private float rotateSpeed = 200f;
private bool _lockMouse;
private float _moveSpeed;
private Vector2 _rotation = Vector2.zero;
private void Update()
{
// check for activate and deactivate input
if (Input.GetMouseButtonDown(1)) Activate();
if (Input.GetMouseButtonUp(1)) Deactivate();
if (_lockMouse)
{
// rotate camera
float xDelta = Input.GetAxis("Mouse X");
float yDelta = Input.GetAxis("Mouse Y");
UpdateRotation(xDelta, yDelta);
}
// update moveSpeed
_moveSpeed = Input.GetKey(KeyCode.LeftShift) || Input.GetKey(KeyCode.RightShift)
? shiftSpeed
: normalSpeed;
// move player
float horizontal = Input.GetAxis("Horizontal");
float vertical = Input.GetAxis("Vertical");
UpdateLocation(horizontal, vertical);
}
private void UpdateRotation(float xDelta, float yDelta)
{
// loop x values after full rotation
_rotation.x = (_rotation.x + xDelta * Time.deltaTime * rotateSpeed) % 360;
// prevent over rotation on y axis
_rotation.y = Mathf.Clamp(_rotation.y - yDelta * Time.deltaTime * rotateSpeed, -90, 90);
// apply rotation to the transform
transform.rotation = Quaternion.Euler(_rotation.y, _rotation.x, 0);
}
private void UpdateLocation(float horizontal, float vertical)
{
// create variables to control movement
Transform t = transform;
Vector3 moveVector = Vector3.zero;
// add horizontal and vertical movement
moveVector += t.right * horizontal;
moveVector += t.forward * vertical;
// adjust movement vector to stop faster diagonal movement
if (moveVector.magnitude > 1) moveVector.Normalize();
// apply movement to transform
t.position += moveVector * Time.deltaTime * _moveSpeed;
}
private void Activate()
{
_lockMouse = true;
Cursor.visible = false;
Cursor.lockState = CursorLockMode.Confined;
}
private void Deactivate()
{
_lockMouse = false;
Cursor.visible = true;
Cursor.lockState = CursorLockMode.None;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment