I want to make my character stop or slow down whenever it's attacking

I want to make my character stop or slow down whenever it’s attacking. I tried changing the velocity to Vector2.Zero:

extends CharacterBody2D


var attacking: bool = false


func _ready():
	%AnimationPlayer.animation_finished.connect(_on_animation_finished)


func _physics_process(delta):
	var direction = Input.get_vector("move_left", "move_right", "move_up", "move_down")
	velocity = direction * 400
	move_and_slide()
	
	if not attacking:
		if velocity.length() > 0.0:
			%Bluwee.play_run()
		else:
			%Bluwee.play_idle()
	
	if Input.is_action_just_pressed("attack") and not attacking:
		attacking = true
		%Bluwee.play_attack()
		velocity = Vector2.ZERO


func _on_animation_finished(animation: String):
	if animation == "side_attack":
		attacking = false
		%Bluwee.play_idle()

There is no error in the code when I execute it, but I don’t understand why changing the velocity doesn’t work.

This should be the easiest solution

func _physics_process(delta):
	var direction = Input.get_vector("move_left", "move_right", "move_up", "move_down")
	if attacking:
		velocity = Vector2.ZERO
	else:
		velocity = direction * 400
	move_and_slide()
1 Like

yes that works, thank you. But do you know why what I did, didn’t work?

1 Like

Your character only moves when move_and_slide is being called and you set the velocity before move_and_slide to a new value, which ignores your other velocity value.
Basically your “velocity = Vector2.ZERO” call gets overwritten. It would have also failed because you set the velocity again if you are attacking or not. The new code checks if you are attacking and only if not it sets the velocity.

In general: Look up state machines on youtube, you already had 2 problems which can be easily fixed by using state-machines. They are a fundamental building block in gamedev

1 Like

okay, I understand, thank you

1 Like

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.