How to rotate object by X degrees with Y speed C#

Hi. I’ve been trying to get this to work for a few days now and couldn’t find an exact answer for what I needed, after scouring Google and the Unity forums.

I’m trying to rotate an object by a certain amount of degrees, with a fixed speed. Looking on the forums I’ve found how to rotate an object just using time, but I need a rotation speed, not a time in which to rotate the object. The reason why I need this is because I’m setting the target rotation with a gesture (swiping) and then I need the object to follow rotating at a certain speed. Here’s the code:

	void Update () 
	{
		if (shouldRotate == true) 
		{
			Rotate2 (rotateBy);
		}
	}

	public void Rotate2(float rotationAngle)
	{
		Quaternion oldRotation = transform.rotation;
		transform.Rotate(0,0,rotationAngle);
		Quaternion newRotation = transform.rotation;

		transform.rotation = Quaternion.Slerp(oldRotation, newRotation, Time.time * rotateSpeed);

		shouldRotate = false;
	}

At the moment I’m calling shouldRotate = true by pushing E from the controller class. The problem is that the object moves the amount of degrees IMMEDIATELY, not slowly. I’ve tried modifying the speed but the rotation is INSTANT, which leads me to believe there’s a problem with my code. Let me know what you think.

Wiz

There are a several things wrong in this code, and without understand what you are trying to do, I cannot figure out how to redo this code so it gives you what you want. If ‘rotationAngle’ represents degrees per second, you can do:

transform.Rotate(0,0,rotationAngle * time.deltaTime);

Another way is to use Quaternion.RotateTowards(). If you execute something like the following each frame from Update():

 transform.rotation = Quaternion.RotateTowards(transform.rotation, newRotation, Time.deltaTime * rotateSpeed); 

But you cannot mixing and matching the two as you’ve done here both has problems, and any working result would be UGLY. Note the use of ‘Time.deltaTime’, not ‘Time.time’.

In general if you know the destination of your rotation, use RotateTowards() and set the destination once (not repeatedly each frame). If you just want the object to spin, use Transform.Rotate().