kinematicbody rotation (following slope angle)

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

Hi! How can I calculate rotation of KinematicBody (3D) to make it following a slopes?

Right now my “box” is moving very well using move_and_slide but I would like to rotate it in natural way to keep both sids on the floor like on attached picture (first is how it’s working and second is what I would like to achieve:

:bust_in_silhouette: Reply From: billyb

So move and slide has a companion function that returns KinematicCollision2D objects:
do something like this

… move and slide …
if get_slide_count() > 0:
var collision = get_slide_collision(0)
var normal = collision.normal()
var angleDelta = normal.angle() - (rotation - PI)
rotation = angleDelta + rotation

If this is in a script attached to your Kinematic Body2D, then rotation is a buildin variable that imediately affects rotation.

Not so sure about the - PI, but your normal will be pointing away from the surface, and depending our your object, it might be PI * .5 or something. Experiment.
Note too, that when one of the angles crosses from -PI to +PI, you might need to flip things around. I’d use some print() statements to monitor the values you’re getting for the angles in your setup.
Note in the above I’m just taking the first collision with get_slide_collision(0); check the api for details.