Created
May 19, 2020 19:03
-
-
Save igrir/222a8e935695382dbe0569589f0cf222 to your computer and use it in GitHub Desktop.
A simple camera orbit for mouse input.
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; | |
using System.Collections; | |
using System.Collections.Generic; | |
using UnityEngine; | |
public class CameraOrbit : MonoBehaviour | |
{ | |
private Vector3 startMMBMousePos; | |
private Vector3 startMMBTransformPos; | |
private Vector3 startRMBMousePos; | |
private Vector3 touchStart; | |
public float groundZ = 0; | |
private Vector3 currentZTouch; | |
// Start is called before the first frame update | |
void Start() | |
{ | |
} | |
private Vector3 camPos; | |
// Update is called once per frame | |
void Update() | |
{ | |
// scroll | |
Vector2 zoomSpeed = Input.mouseScrollDelta; | |
this.transform.position = this.transform.position + (this.transform.forward * zoomSpeed.y * Time.deltaTime * 50); | |
// pan | |
if (Input.GetMouseButtonDown(2)) | |
{ | |
touchStart = GetWorldPosition(groundZ); | |
} | |
if (Input.GetMouseButton(2)) | |
{ | |
currentZTouch = GetWorldPosition(groundZ); | |
Vector3 direction = touchStart - GetWorldPosition(groundZ); | |
Camera.main.transform.position += direction; | |
} | |
// rotation | |
if (Input.GetMouseButtonDown(1)) | |
{ | |
startRMBMousePos = Input.mousePosition; | |
} | |
if (Input.GetMouseButton(1)) | |
{ | |
Vector3 deltaPos = Input.mousePosition - startRMBMousePos; | |
float yaw = (deltaPos.x / 2000) * 360; | |
float pitch = (deltaPos.y / 2000) * 360; | |
float roll = -pitch; | |
this.transform.Rotate(Vector3.up, yaw); | |
this.transform.Rotate(Vector3.left, pitch); | |
this.transform.rotation = Quaternion.Euler(this.transform.rotation.eulerAngles.x, this.transform.rotation.eulerAngles.y, 0); | |
startRMBMousePos = Input.mousePosition; | |
} | |
} | |
private Vector3 GetWorldPosition(float z){ | |
Ray mousePos = Camera.main.ScreenPointToRay(Input.mousePosition); | |
Plane ground = new Plane(this.transform.forward, this.transform.position + this.transform.forward * 10); | |
float distance; | |
ground.Raycast(mousePos, out distance); | |
return mousePos.GetPoint(distance); | |
} | |
private void OnDrawGizmos() | |
{ | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment