Move CharacterBody2d in set direction for x time

Godot Engine v4.2.2.stable.official.15073afe3

So my goal is to move CharacterBody2d in a direction for set amount of time and set amount of speed. This should work if the player in not pressing direction buttons.
I am kinda at a loss. I was expecting this to move character indefinitely until the bool is changed. But it ran only once. I am new to programming and godot in general. Sorry for a stupid question.

func rolling(delta):
if is_rolling==true:
velocity.x = direction_facing9000delta


I implemented the solution and posted it here if you want:

But here are the big lines:

You will want to define a goal position that you want to reach in X seconds
At that point you have everything you need for the operation.

You get the difference with your actual position:

var difference: Vector2 = goal - position

and by dividing the difference with the time you want to take, you will know how much you need to add per second

value_to_add_per_second = difference / travel_time

With all that, you now need to add the value_to_add_per_second to your current position in a process function:

func _physics_process(p_delta):
	if time_needed_to_add > 0:
		time_needed_to_add -= p_delta
		# Set the value to avoid us some trouble with floating points
		if time_needed_to_add <= 0: 
			position = goal_position
			position += value_to_add_per_second * p_delta

You might have notice that the value_to_add_per_second is multiplied by delta,
it is done so to accomodate your “per_second_calcul” with how often the process is called.

I hope it helped!

Interesting but not what am looking for (but thank you I am 100% sure I will use it!) . I am starting to think I can achieve what I want with animation node.

1 Like

Oh, I see what I’ve misunderstood, sorry.

If it only executes once, it’s because the velocity is changed.

Current velocity vector in pixels per second, used and modified when calling [move_and_slide].

At least that’s what I think, because I don’t use CharacterBody2D in my game.

It might work as you expect if you set it every frame:

func _process(delta) :
    if is_rolling == true :
        velocity.x = direction_facing * 9000 * delta
1 Like

Ah yes I get what I missed now! Thanks. Also default values of move_and_slide() interfere with it.

1 Like