I want to Make A 2D Character move towards one direction until collides with platform

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

I want a character to move in one direction until it collides with a platform for my platform game. Gravity is not required. I know there are many ways. But I couldn’t find one, as I am new to coding and Godot.I am using a Kinematic Body 2D As the Character node.

:bust_in_silhouette: Reply From: p7f

Hi! I commented about this in your other question. If you are using a kinematicbody2d and move it with move_and_slide, just passing a constant vector to that function will keep it moving until something block its way. Would you share what code you have already implemented? For example, if you want to keep moving to right, you can just do something like:

var velocity = Vector2(100,0) # Can be any vector2

func _physics_process(delta):
    velocity = move_and_slide(velocity, Vector2.UP)

that will keep moving to right untill it hits something. If it can slide trhough it (like a slope for example) it will adjust the movement.
Is that what you are looking for?

EDIT: Seeing your comment in your other question, i think the problem is that you are reseting velocity to zero when not pressing any action, is that right? That would stop movement… if you want to keep moving, you should not reset velocity.

And instead of adding velocity.x += 1 for example, when a key is pressed you could just replace the current value velocity.x = 1 so if it was moving in some direction and you press another key, it will start moving the other way.