Enemy Won't Dash

Godot Version

v4.6.2

Question

I’m making a 2D Metroidvania Enemy that is meant to dash towards the player once the player is in range, but it’s not working.

There are no error messages.

Here is the code:

extends CharacterBody2D

@export var speed  = 500
@onready var chip: CharacterBody2D = $"../../Chip"
@onready var wait: Timer = $Dashwait

var chipdir
var chippos
var dashspeed = 1000
var state = 0

# Called every frame. 'delta' is the elapsed time since the previous frame.
func _process(delta: float) -> void:
	if global_position.distance_to(chip.global_position) < 1500 and global_position.distance_to(chip.global_position) > 500:
		state = 1
		speed = 500
		if global_position.distance_to(chip.global_position) < 800:
			speed = 400
		if global_position.distance_to(chip.global_position) < 700:
			speed = 300
		if global_position.distance_to(chip.global_position) < 600:
			speed = 200
	elif global_position.distance_to(chip.global_position) < 500 and wait.is_stopped():
		state = 2
		chipdir = global_position.direction_to(chip.global_position)
		chippos = chipdir * speed

func _physics_process(delta: float) -> void:
	if state == 0:
		pass
	elif state == 1:
		var target_direction = global_position.direction_to(chip.global_position)
		var target_velocity = target_direction * speed
		velocity = velocity.move_toward(target_velocity, speed)
		move_and_slide()
	elif state == 2:
		velocity = velocity.move_toward(chippos, speed)
		print(chipdir,"-",chippos)
		#velocity = move_toward()

Does this line never prints anything? print(chipdir,"-",chippos)
If so, make sure your timer is actually stopped, that it’s not set to autostart, or is not looping or somethng.

It wasn’t set to autostart and probably not looping, as when the enemy stops when it gets in range of the player, the two values stay constant until the player moves away.

Its definitely a problem with this section of the code:

	elif state == 2:
		velocity = velocity.move_toward(chippos, speed)
		print(chipdir,"-",chippos)
		wait.start()

Does this print? If so, can you share what it prints?

Its supposed to move using these two variables, but it isn’t working

What is the purpose of dashspeed variable?

I cant see you using the velocity anywhere. You just set it. If it is state 2 we are talking about. State 1 has a move_and_slide()

1 Like

It is the speed of the dash, I forgot to replace the speed with dashspeed.

Thanks this worked!

1 Like