Skip to content

Instantly share code, notes, and snippets.

@julenka
Forked from RyanBreaker/FlyCamera.cs
Last active March 29, 2020 23:29
Show Gist options
  • Save julenka/aae5b908664f45e2aac8bb7cbd54bcac to your computer and use it in GitHub Desktop.
Save julenka/aae5b908664f45e2aac8bb7cbd54bcac to your computer and use it in GitHub Desktop.
Unity Script to give camera WASD + mouse control when right mouse clicked
using UnityEngine;
using System.Collections;
public class FlyCamera : MonoBehaviour
{
/*
Writen by Windexglow 11-13-10. Use it, edit it, steal it I don't care.
Converted to C# 27-02-13 - no credit wanted.
Reformatted and cleaned by Ryan Breaker 23-6-18
Added Q/E keys to move up/down and only move mouse when right button clicked by Julia Schwarz 29-3-20
Original comment:
Simple flycam I made, since I couldn't find any others made public.
Made simple to use (drag and drop, done) for regular keyboard layout.
Controls:
WASD : Directional movement
Shift : Increase speed
Space : Moves camera directly up per its local Y-axis
*/
public float mainSpeed = 10.0f; // Regular speed
public float shiftAdd = 25.0f; // Amount to accelerate when shift is pressed
public float maxShift = 100.0f; // Maximum speed when holding shift
public float camSens = 0.15f; // Mouse sensitivity
private Vector3 lastMouse = new Vector3(255, 255, 255); // kind of in the middle of the screen, rather than at the top (play)
private float totalRun = 1.0f;
private void Start()
{
lastMouse = Input.mousePosition;
}
void Update()
{
if(Input.GetMouseButton(1))
{
MoveCamera();
}
lastMouse = Input.mousePosition;
}
private void MoveCamera()
{
// Mouse camera angle done.
var mouseDelta = Input.mousePosition - lastMouse;
transform.eulerAngles += new Vector3(-mouseDelta.y * camSens, mouseDelta.x * camSens, 0);
// Keyboard commands
Vector3 p = GetBaseInput();
if (Input.GetKey(KeyCode.LeftShift))
{
totalRun += Time.deltaTime;
p *= totalRun * shiftAdd;
p.x = Mathf.Clamp(p.x, -maxShift, maxShift);
p.y = Mathf.Clamp(p.y, -maxShift, maxShift);
p.z = Mathf.Clamp(p.z, -maxShift, maxShift);
}
else
{
totalRun = Mathf.Clamp(totalRun * 0.5f, 1f, 1000f);
p *= mainSpeed;
}
p *= Time.deltaTime;
transform.Translate(p);
}
// Returns the basic values, if it's 0 than it's not active.
private Vector3 GetBaseInput()
{
Vector3 p_Velocity = new Vector3();
// Forwards
if (Input.GetKey(KeyCode.W))
p_Velocity += new Vector3(0, 0, 1);
// Backwards
if (Input.GetKey(KeyCode.S))
p_Velocity += new Vector3(0, 0, -1);
// Left
if (Input.GetKey(KeyCode.A))
p_Velocity += new Vector3(-1, 0, 0);
// Right
if (Input.GetKey(KeyCode.D))
p_Velocity += new Vector3(1, 0, 0);
// Up
if (Input.GetKey(KeyCode.Q))
p_Velocity += new Vector3(0, 1, 0);
// Down
if (Input.GetKey(KeyCode.E))
p_Velocity += new Vector3(0, -1, 0);
return p_Velocity;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment