1
\$\begingroup\$

I've managed to get my sprite enemies shoot at the player with

@export var bullet_speed  = 100

@onready var p = get_node("/root/main/player")
@onready var target_pos = p.global_position

func _physics_process(delta):
    var dir = self.global_position.direction_to(target_pos)
    global_position.x += (dir.x * bullet_speed) * delta
    global_position.y += (dir.y * bullet_speed) * delta

However, the projectiles will reach their destination and then stop. I'm not sure why. I thought I was get the angle between them and send them off in that direction (until they get to edge of the screen), rather than a location.

I need them to overshoot so the projectiles move beyond their original target. Do I need to do a bit of trig, calculate the opposite and adjacent, double it and then send them to that location?

\$\endgroup\$

1 Answer 1

3
\$\begingroup\$

In you code, you care computing the direction form the current position to the target every (physics) frame:

func _physics_process(delta):
    var dir = self.global_position.direction_to(target_pos)

By the way, the direction is not an angle, it is a normalized vector.

Since you are computing it every (physics) frame, if and when your object reaches the target it wouldn't have a direction to move.


To have the behavior you want, you should compute the direction once and keep using it.

For example:

@export var bullet_speed  = 100

@onready var p = get_node("/root/main/player")
@onready var dir = global_position.direction_to(p.global_position)

func _physics_process(delta):
    global_position.x += (dir.x * bullet_speed) * delta
    global_position.y += (dir.y * bullet_speed) * delta

Alternatively, you could do it in _ready instead.

No trigonometry involved. It is pretty much forgetting about the target, and just go in a direction.

\$\endgroup\$

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .