Skip to content

Instantly share code, notes, and snippets.

@filp
Created April 23, 2019 17:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save filp/7e2c5a2c884a67a3c73ba25ec18c88f2 to your computer and use it in GitHub Desktop.
Save filp/7e2c5a2c884a67a3c73ba25ec18c88f2 to your computer and use it in GitHub Desktop.
using UnityEngine;
public class CameraController : MonoBehaviour
{
[Header("Camera Movement Options")]
public float keyboardPanSpeed = 100f;
public float mousePanSpeed = 50f;
public float mousePanBaseSpeed = 0.01f;
public float zoomSpeed = 50f;
public float edgeSize = 20f;
[Header("Camera Pan Boundaries")]
public float minX = 0;
public float maxX = 0;
public float minY = 0;
public float maxY = 0;
public float minZ = 0;
public float maxZ = 0;
private bool movementEnabled = true;
private Vector3 cameraStartPosition;
void Start () {
cameraStartPosition = transform.position;
}
void Update () {
// Toggle movement on/off with Escape key:
if (Input.GetKeyDown(KeyCode.Escape)) {
movementEnabled = !movementEnabled;
// Reset camera position when movement is disabled:
if (!movementEnabled) {
transform.position = cameraStartPosition;
}
}
if (!movementEnabled) return;
// Calculate pan/zoom from keyboard/controller axis:
Vector3 keyboardTranslate = new Vector3(
(Input.GetAxisRaw("Horizontal") * keyboardPanSpeed) * Time.deltaTime,
-Input.GetAxisRaw("Mouse ScrollWheel") * zoomSpeed,
(Input.GetAxisRaw("Vertical") * keyboardPanSpeed) * Time.deltaTime
);
// Calculate pan from edge positioning:
Vector3 mouseTranslate = new Vector3(
(EdgeTranslate(Input.mousePosition.x, Screen.width) * mousePanSpeed) * Time.deltaTime,
0,
(EdgeTranslate(Input.mousePosition.y, Screen.height) * mousePanSpeed) * Time.deltaTime
);
transform.Translate(
keyboardTranslate + mouseTranslate,
Space.World
);
transform.position = new Vector3(
Mathf.Clamp(transform.position.x, minX, maxX),
Mathf.Clamp(transform.position.y, minY, maxY),
Mathf.Clamp(transform.position.z, minZ, maxZ)
);
}
float EdgeTranslate (float position, float boundary) {
if (position > 0 && position <= edgeSize) {
return -mousePanBaseSpeed * (edgeSize - position);
} else if (position > (boundary - edgeSize) && position <= boundary) {
return mousePanBaseSpeed * (edgeSize - (boundary - position));
} else {
return 0;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment