How to rotate an object at specific angle with a specific direction and speed?

2.1k Views Asked by At

I want to rotate an object by some specific degree, speed and direction in Z-axis and then stop.

This is my code:

Quaternion targetRotation = Quaternion.AngleAxis(currentRotation.rotateValue, Vector3.forward);
float step = currentRotation.speed;
transform.rotation = Quaternion.RotateTowards(transform.rotation, targetRotation, step);

With this, I can move with desired speed and angle but the direction is not correct. What I do is move it by 180 after it reaches 180 I move it by 360 and this is in a loop. The problem is that after 360 instead of moving clockwise it moves counter clockwise. Not sure what is going on here need desperate help on this one.

Thanks in advance.

1

There are 1 best solutions below

0
On

If I understand correctly what you are trying to do, then maybe something like this would work:

private float anglesToRotate;
private Quaternion targetRotation, initialRotation;
private float elapsedTime, duration, speed;

void Start()
{
    time = 0.0f;
    duration= 0.0f;
}

void Update()
{
    if (time < duration)
    {
        time += Time.deltaTime;
        transform.rotation = Quaternion.Lerp(
                                  initialRotation,
                                  targetRotation,
                                  (speed * time) / duration);
    }
}

public void Rotate(float angles, float speed, float duration)
{
     initialRotation = transform.rotation;
     targetRotation = Quaternion.Euler(
                         transform.rotation.x,
                         transform.rotation.y,
                         transform.rotation.z + anglesToRotate);
     time = 0.0f;
}

NOTES:

  • Use positive angles to rotate in one direction and negative to rotate in the opposite direction (if angles is 180 then the sign will not matter).
  • Play with the value of speed and duration to make the rotation to be faster or slower. (I had to add duration to make it work with Quaternion.Lerp).
  • I have not tested this, so I am not sure if it will work as expected.