Drag on an object to move the view around.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
/* place on whatever object you want people to start dragging from. (so script can access "OnMouseDown()" event)
*/
public class mouseLookin : MonoBehaviour
{
public Camera mainCamera; //place main game camera here. it will be rotated by mouse dragging
public float speed = 100.0f; //modifies how fast the view moves. exposed so you can tweak in editor
public float clampAngle = 80.0f; // hard limit the up/down rotation to +/- this amount
private float rotY = 0.0f; // horizontal rotation (around the y axis)
private float rotX = 0.0f; // vertical rotation (around the x axis)
bool movingView = false; // flag for whether we are currently dragging view around
/* when program starts, set initial values (so the first use doesn't snap view to some weird angle)
*/
void Start()
{
Vector3 rot = mainCamera.transform.localRotation.eulerAngles; // grab the camera's starting rotation.
rotY = rot.y;
rotX = rot.x;
}
/* when you press down (*or hold) mouse button - over the object this script is on
*/
void OnMouseDown()
{
movingView = true; //enables per frame stuff in Update() (below)
}
/* whenever you stop dragging with your mouse
* note that this is mouseup anywhere (even if you are way far away from object that started it)
*/
void OnMouseUp()
{
movingView = false; //stops the mouse look
}
void Update()
{
if (movingView)
{
Cursor.visible = false; //hide the cursor so it's not distracting while we look around
float mouseX = Input.GetAxis("Mouse X"); //get left/right
float mouseY = -Input.GetAxis("Mouse Y"); //get up/down
rotY += mouseX * speed * Time.deltaTime; //rotate around Y axis, using mouse left/right, boost by speed, boost by time between frames
rotX += mouseY * speed * Time.deltaTime; //rotate around X axis, using mouse up/down (and boost by speed, boost by time between frames)
rotX = Mathf.Clamp(rotX, -clampAngle, clampAngle); //restrict up/down motion between + or - the clampAngle we set above. So we can only look so far up and down.
Quaternion localRotation = Quaternion.Euler(rotX, rotY, 0.0f); //convert rotations to something Unity natively understands
mainCamera.transform.rotation = localRotation; //apply rotation to the camera we set in Editor
}
else
{
Cursor.visible = true; //whenever we are not looking around, show the cursor
//!!! this might be better handled in another "master" cursor management script, if other scripts want to show and hide the cursor
}
}
/* called externally: by a "turn speed" UI slider
*/
public void setMouseLookSpeed(float s)
{
speed = s;
}
}