Home > Blockchain >  Using MoveRotation in Unity 3D to turn player towards a certain angle
Using MoveRotation in Unity 3D to turn player towards a certain angle

Time:11-04

I've been told that Rigidbody.MoveRotation is the best way in Unity 3D to rotate the player between fixed positions while still detecting hits. However, while I can move smoothly from fixed position to position with:

if (Vector3.Distance(player.position, targetPos) > 0.0455f) //FIXES JITTER 
            {
                var direction = targetPos - rb.transform.position;
                rb.MovePosition(transform.position   direction.normalized * playerSpeed * Time.fixedDeltaTime);
            }

I can't find out how to rotate smoothly between fixed positions. I can rotate to the angle I want instantly using Rigidbody.MoveRotation(Vector3 target);, but I can't seem to find a way to do the above as a rotation. Note: Vector3.Distance is the only thing stopping jitter. Has anyone got any ideas?

CodePudding user response:

So, you want to animate the rotation value over time until it reaches a certain value.

Inside the Update method, you can use the Lerp method to keep rotating the object to a point, but you will never really reach this point if you use Lerp. It will keep rotating forever (always closer to the point).

You can use the following:

private bool rotating = true;
public void Update()
{
    if (rotating)
    {
        Vector3 to = new Vector3(20, 20, 20);
        if (Vector3.Distance(transform.eulerAngles, to) > 0.01f)
        {
            transform.eulerAngles = Vector3.Lerp(transform.rotation.eulerAngles, to, Time.deltaTime);
        }
        else
        {
            transform.eulerAngles = to;
            rotating = false;
        }
    }
 
}

So, if the distance between the current object angle and the desired angle is greater than 0.01f, it jumps right to the desired position and stop executing the Lerp method.

CodePudding user response:

You can go one step further and use a tweeting library to tween between rotations.

DOTween

With that you can call it like this:

transform.DoRotate(target, 1f) to rotate to target in 1 second.

Or even add callbacks.

transform.DoRotate(target, 1f).OnComplete(//any method or lambda you want)

  • Related