Rotate gameobject by mouse at constant speed?

Helo, I want to rotate a game object at a constant speed by holding right-click on it and then dragging the mouse in the direction(only left and right) in which you want to rotate the GO.

``````if (Input.GetMouseButton(1))
{
gameObject.transform.Rotate(new Vector3(0, -Input.GetAxis("Mouse X"), 0));
}
``````

This is the code I’m using and it works, but if I drag the mouse faster, the rotation will also be faster. I want to rotate the object at a constant speed, no matter how fast I’m dragging the mouse.

You need to store your mouse input and use that to check if you are moving to the right or to the left, and then if you hold right-click and mouseX > 0 or mouseX < 0 do rotate (which is a simple transform.Rotate (axis, angle).

Here is a code that works and also lets you change the axis in the inspector with a simple enum:

``````using UnityEngine;

public class ConstantRotationUsingMouseInput : MonoBehaviour
{
public enum RotationAxis { x, y, z }
public RotationAxis rotationAxis;

private float mouseX;

private void Update()
{
mouseX = Input.GetAxis("Mouse X");

if (Input.GetMouseButton(1))
{
if (mouseX > 0)
Rotate(-5);
else if (mouseX < 0)
Rotate(5);
}
}

private void Rotate(float rate)
{
Vector3 axis = Vector3.zero;
switch (rotationAxis)
{
case RotationAxis.x:
axis = Vector3.right;
break;
case RotationAxis.y:
axis = Vector3.up;
break;
case RotationAxis.z:
axis = Vector3.forward;
break;
default:
break;
}
transform.Rotate(axis, rate);
}
}
``````

What you’ll wanna do is lerp. something like this might help (untested, but should give you an idea)

``````void Update()
{
if (Input.GetMouseButton(1))
{
StartRotation(transform.eulerAngles, new Vector3(0, -Input.GetAxis("Mouse X"), 0));
}
}

private float _timeStartedLerping, lastRotationTime;
private Vector3 _startPosition;
private Vector3 _endPosition;
[SerializeField] float rotSpeed; // speed at which to rotate serialized so we can see it in the inspector
private void StartRotation(Vector3 start, Vector3 end)
{
_timeStartedLerping = Time.time;

_startPosition = start;
_endPosition = end;
}

private void FixedUpdate()
{
{
float timeSinceStarted = Time.time - _timeStartedLerping;
float percentageComplete = timeSinceStarted / rotSpeed;

transform.eulerAngles = Vector3.Lerp(_startPosition, _endPosition, percentageComplete);

if (percentageComplete >= 1.0f)
{