0 votes

So I was following a GD quest tutorial on 2d platformer and noticed that although everything works well when I tried to add a slope in game the box just climb it without rotating along side the degree of the slope. The box is a kinematic body 2d and i am using move and slide(linear_velocity, up direction(0,-1)) to control it. I look up the documents and figure that move and slide could be used to handle slopes but I just couldn't find a way to do that.

Godot version v3.2.3.stable.offical
in Engine by (12 points)

1 Answer

0 votes

You can get the floor normal using get_floor_normal, then set the rotation of your sprite to be equal to the angle of the floor normal.
Note that you should call get_floor_normal after calling move_and_slide(). You can also use the is_on_floor() method to check if the player is on floor and only get the normal then.

So, the code could look something like this:

func _process(delta: float) -> void:
   # Some code for getting the velocity, applying gravity, etc

   move_and_slide(velocity, Vector2.UP)

   if is_on_floor():
      var normal: Vector2 = get_floor_normal()
      $Sprite.rotation = normal.angle()

Depending on your sprite, you might need to apply an offset to the rotation in order to align your it properly with the floor tho.

var offset: float = deg2rad(90)
$Sprite.rotation = normal.angle() + offset

The angle() method returns the angle of the vector in radians. You can use deg2rad() and rad2deg() to convert them into each other.

Edit: Formating and spelling errors.

by (178 points)
edited by
Welcome to Godot Engine Q&A, where you can ask questions and receive answers from other members of the community.

Please make sure to read Frequently asked questions and How to use this Q&A? before posting your first questions.
Social login is currently unavailable. If you've previously logged in with a Facebook or GitHub account, use the I forgot my password link in the login box to set a password for your account. If you still can't access your account, send an email to [email protected] with your username.