- Home /
Restrict camera rotation
I've found this script that works perfectly for how I want the camera to move. I want to restrict it so you can't look all the way around. I've looked at mathf and clamp functions, but being a total noob, I mess up the whole thing whenever I try to do anything.
using UnityEngine;
using System.Collections;
public class MouseView : MonoBehaviour
{
public float Sensitivity = 0.125f;
Vector3 _prevMousePosition = Vector3.zero;
float _tilt = 0;
float _turn = 0;
void Update ()
{
Vector3 mousePosition = Input.mousePosition;
if( Input.GetMouseButton( 0 ) )
{
_tilt += -( mousePosition.y-_prevMousePosition.y ) * Sensitivity;
_turn += ( mousePosition.x-_prevMousePosition.x ) * Sensitivity;
}
_prevMousePosition = mousePosition;
transform.localRotation = Quaternion.Euler( _tilt, _turn, 0 );
}
}
Also, I want to reset the view/script when "v" is pressed.
Any advice would be much appreciated.
Answer by fabian-mkv · Apr 22, 2016 at 12:09 AM
First, define the range with these 4 variables:
float minTiltAngle = -45f;
float maxTiltAngle = 90f;
float minTurnAngle = -60f;
float maxTurnAngle = 60f;
Then, Immediately after setting _tilt and _turn, you could clamp them like so:
_tilt += Mathf.Clamp(_turn, minTiltAngle, maxTiltAngle);
_turn = Mathf.Clamp(_turn, minTurnAngle, maxTurnAngle);
For your "v to reset" problem, try putting this in the Update function:
if (Input.GetKeyDown(KeyCode.V)) {
tilt = 0f;
turn = 0f;
}
Update gets called every frame. when the player presses V for the first time, GetKeyDown for the key V will return true. If the player keeps holding it, this function will not be true for subsequent frames. If you want to check every frame whether a key is being held down, use Input.GetKey
All put together: using UnityEngine; using System.Collections;
public class MouseView : MonoBehaviour
{
public float Sensitivity = 0.125f;
Vector3 _prevMousePosition = Vector3.zero;
float _tilt = 0;
float _turn = 0;
float minTiltAngle = -45f;
float maxTiltAngle = 90f;
float minTurnAngle = -60f;
float maxTurnAngle = 60f;
void Update ()
{
Vector3 mousePosition = Input.mousePosition;
if( Input.GetMouseButton( 0 ) )
{
_tilt += -( mousePosition.y-_prevMousePosition.y ) * Sensitivity;
_turn += ( mousePosition.x-_prevMousePosition.x ) * Sensitivity;
_tilt += Mathf.Clamp(_turn, minTiltAngle, maxTiltAngle);
_turn = Mathf.Clamp(_turn, minTurnAngle, maxTurnAngle); }
_prevMousePosition = mousePosition;
transform.localRotation = Quaternion.Euler( _tilt, _turn, 0 );
}
if (Input.GetKeyDown(KeyCode.V)) {
tilt = 0f;
turn = 0f;
}
}
Your answer
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
Making a bubble level (not a game but work tool) 1 Answer
Prevent Reset() from clearing out serialized fields 2 Answers