Is there a way to use move_and_slide() with different velocity?

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

Hey, I tried following a tutorial, however the move_and_slide() function doesn’t get a different velocity. I tried using the velocity instead of the knockback variable, however this gets the situation pretty rough and clunky.
This is the original code by HeartBeast:

var knockback = Vector2.ZERO
func _physics_process(delta):
	knockback = knockback.move_toward(Vector2.ZERO, FRICTION * delta)
	knockback = move_and_slide(knockback)
func _on_hurtbox_area_entered(area):
	knockback = area.knockback_vector * 120

I was using velocity that way:

func _physics_process(delta):
    velocity = velocity.move_toward(Vector2.ZERO, 100 * delta)
    move_and_slide()

func _on_hurtbox_area_entered(area):
    velocity = area.knockback_vector * 100

If anyone has a solution or an idea please let me know :slight_smile:

maybe something like this

var knockback = Vector2.ZERO

func _physics_process(delta):
	var old_velocity = velocity
    knockback = knockback.move_toward(Vector2.ZERO, FRICTION * delta)
    velocity = knockback
	move_and_slide()
	knockback = velocity
	velocity = old_velocity

func _on_hurtbox_area_entered(area):
    knockback = area.knockback_vector * 120

LazyBigCat | 2023-03-04 19:40

Thank you it helped me a lot.
I have combined this with another solution I saw:

func _on_hurtbox_area_entered(area):
	stats.health -= area.damage
	var direction = ( position - area.owner.position ).normalized()
	knockback = direction * KNOCKBACK_SPEED
func _physics_process(delta):
	var old_velocity = velocity
	knockback = knockback.move_toward(Vector2.ZERO, FRICTION * delta)
	velocity = knockback
	move_and_slide()
	knockback = velocity
	velocity = old_velocity

It helped me and I hope it would help anyone who also comes across it!

MegaLuiza | 2023-03-05 10:19