Rotate to four directions

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By pnsadeghy

I have a code like this

func _physics_process(delta):
        if Input.is_action_pressed("up"):
              rd = 0
        elif Input.is_action_pressed("down"):
              rd = 180
        elif Input.is_action_pressed("right"):
              rd = 90
        elif Input.is_action_pressed("left"):
              rd = -90

        rotation_degrees = lerp(rotation_degrees, rd, 0.1)

It works well, but the problem is that when turning from left to down or from down to left, the object makes a complete turn that not interesting!

How can I have the correct rotation?

Have you tried using lerp_angle() instead of lerp()?

magicalogic | 2023-01-02 07:46

I tried and its works. thanks

pnsadeghy | 2023-01-03 19:07

:bust_in_silhouette: Reply From: SteveSmith

Reduce the 0.1 to something smaller.

:bust_in_silhouette: Reply From: SQBX

Try this:

func _physics_process(delta):
    if Input.is_action_pressed("up"):
          rd = 0
    elif Input.is_action_pressed("down"):
          rd = 180
    elif Input.is_action_pressed("right"):
          rd = 90
    elif Input.is_action_pressed("left"):
          rd = -90

    rotation= lerp_angle(rotation, rd, 0.1)

lerp_angle is similar to lerp, but interpolates correctly when the angles wrap around @GDScript.TAU. To perform eased interpolation with lerp_angle, combine it with ease or smoothstep.

Note: This function lerps through the shortest path between from and to. However, when these two angles are approximately PI + k * TAU apart for any integer k, it’s not obvious which way they lerp due to floating-point precision errors. For example, lerp_angle(0, PI, weight) lerps counter-clockwise, while lerp_angle(0, PI + 5 * TAU, weight) lerps clockwise.

Thank you so much

pnsadeghy | 2023-01-03 19:06

You’re welcome!

SQBX | 2023-01-03 19:06