How to properly move a KinematicBody2D via code?

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

I’m trying to make a moving platform with a KinematicBody2D and move it from code. It moves to right in a velocity but when it comes back to left, gets slower. Also, “direcao” means direction.

This is how I coded it.

If someone knows what is wrong in the code or some optimal way to do this, it would be very nice.
Thanks for help.

:bust_in_silhouette: Reply From: Socrates

I haven’t tested this code but something like this should work:

onready var velocity = Vector2(100, 0)
var prev_pos_x

func _physics_process(delta)
	if prev_pos_x < end_pos.x and position.x > end_pos.x:
		velocity.x = -100
	elif prev_pos_x > start_pos.x and position.x < start_pos.x:
		velocity.x = 100
		
	position += velocity * delta
		
        prev_pos_x = position.x

It’s also pretty easy to do this in the animation editor, although it gives you less fine control over the velocity

Thank you! I just changed the “if” condition a little bit.

	if $plat.position.x >= end_position.x:
	velocity = -100
	
elif $plat.position.x <= start_position.x:
	velocity = 100

Also, i’m glad that that the player doesn’t shake when on top of the plataform. I think it’s because you didn’t use the “.translate”.

Jutoend | 2018-02-19 19:18