KinematicBody2D movement in 3.0

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

Hey all.

In v2.1.4, a code for moving my player on the map was working well (shown below):

func _fixed_process(delta):
if Input.is_action_pressed("btn_A"):
	set_rot(get_rot() + delta * rotation_speed)
if Input.is_action_pressed("btn_D"):
	set_rot(get_rot() + delta * -rotation_speed)
if Input.is_action_pressed("btn_W"):
	move(Vector2((player_speed * sin(get_rot())) * delta, (player_speed * cos(get_rot())) * delta))

But since I moved to v3.0, I realized that everything is wrong now. I don’t even know if only the code for moving doesn’t work, or the problem is somewhere else.

But my question is: according to the code for movement in v2.1.4, how it should be rewritten for v3.0?

Something like:

func _fixed_process(delta):
if Input.is_action_pressed("btn_A"):
	rotation + delta * rotation_speed
if Input.is_action_pressed("btn_D"):
	rotation + delta * -rotation_speed
if Input.is_action_pressed("btn_W"):
	velocity = Vector2((player_speed * sin(rotation)) * delta, (player_speed * cos(rotation)) * delta))

Or what?
Thank you in advance.

first of all. _fixed_process is changed to _physics_process
try this first.

volzhs | 2018-02-25 17:30

:bust_in_silhouette: Reply From: kidscancode

Here’s how I’d rewrite that:

func _physics_process(delta):
    if Input.is_action_pressed("btn_A"):
        rotation += rotation_speed * delta
    if Input.is_action_pressed("btn_D"):
        rotation -= rotation_speed * delta
    if Input.is_action_pressed("btn_W"):
        velocity = Vector2(player_speed, 0).rotated(rotation)
        move_and_collide(velocity * delta)

Explanation:

  • _fixed_process() is renamed to _physics_process()

  • set_rot(), get_pos(), and other properties are now accessed directly via member variables such as rotation and position. The API reference is a good place to see what they are (autocomplete also will suggest them).

  • move() was replaced with two new movement methods: move_and_collide() which behaves exactly like move() did, and move_and_slide() which provides automatic sliding collision response (useful for platformers, for example).

  • I rewrote your velocity calculation. You’re already using vectors, so it’s redundant to calculate the x and y components individually, when Vector2 has methods to handle rotation already. Also, conceptually velocity is the object’s movement vector, so you shouldn’t include delta directly (multiplying velocity by a time gives you a distance). delta is used to calculate the distance moved in a single frame based on a given velocity.

Finally, note that move_and_collide() returns a KinematicCollision2D object that you can use to calculate your collision response.