Skip to content

Instantly share code, notes, and snippets.

@alexmelyon
Created November 2, 2021 20:44
Show Gist options
  • Save alexmelyon/53eab784050df8a76ac0b0678f2f5eca to your computer and use it in GitHub Desktop.
Save alexmelyon/53eab784050df8a76ac0b0678f2f5eca to your computer and use it in GitHub Desktop.
Unity camera movement like Editor
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CameraEditorMovement : MonoBehaviour
{
[Header("Mouse")]
public float lookSpeedH = 2f;
public float lookSpeedV = 2f;
public float zoomSpeed = 2f;
public float dragSpeed = 6f;
[Header("Keyboard")]
public float normalMoveSpeed = 1F;
public float fastMoveFactor = 5F;
private float yaw = 0f;
private float pitch = 0f;
void Update()
{
// Look around with Right Mouse
if (Input.GetMouseButton(1))
{
yaw += lookSpeedH * Input.GetAxis("Mouse X");
pitch -= lookSpeedV * Input.GetAxis("Mouse Y");
transform.eulerAngles = new Vector3(pitch, yaw, 0f);
}
// Drag camera around with Middle Mouse
if (Input.GetMouseButton(2))
{
transform.Translate(-Input.GetAxisRaw("Mouse X") * Time.deltaTime * dragSpeed, -Input.GetAxisRaw("Mouse Y") * Time.deltaTime * dragSpeed, 0);
}
// Zoom in and out with Mouse Wheel
transform.Translate(0, 0, Input.GetAxis("Mouse ScrollWheel") * zoomSpeed, Space.Self);
handleKeyboard();
}
void handleKeyboard()
{
bool wasd = Input.GetKey(KeyCode.W) || Input.GetKey(KeyCode.S) || Input.GetKey(KeyCode.A) || Input.GetKey(KeyCode.D);
bool arrows = Input.GetKey(KeyCode.UpArrow) || Input.GetKey(KeyCode.DownArrow) || Input.GetKey(KeyCode.LeftArrow) || Input.GetKey(KeyCode.RightArrow);
if (wasd || arrows)
{
transform.position += transform.forward * (normalMoveSpeed * fastMoveFactor) * Input.GetAxis("Vertical") * Time.deltaTime;
transform.position += transform.right * (normalMoveSpeed * fastMoveFactor) * Input.GetAxis("Horizontal") * Time.deltaTime;
}
if (Input.GetKey(KeyCode.Q))
{
transform.position -= transform.up * (normalMoveSpeed * fastMoveFactor) * Time.deltaTime;
}
if (Input.GetKey(KeyCode.E))
{
transform.position += transform.up * (normalMoveSpeed * fastMoveFactor) * Time.deltaTime;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment