0 votes

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.

in Engine by (35 points)
edited by

1 Answer

+1 vote
Best answer

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

by (536 points)
selected by

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".

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.