why doesn't the bullet go towards the player?

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

why doesn’t this code work?

extends Area2D
export(int) var speed = 230
export(int) var damage = 15
onready var player = get_parent().get_node("player")
var velocity = Vector2.ZERO
var target_pos: Vector2

func _ready():
    target_pos = player.global_position
    self.rotation = target_pos.angle()
    velocity = self.global_position.direction_to(target_pos)

func _physics_process(delta):
    self.global_position += velocity * speed * delta

Can you be more specific about “doesn’t work?”

exuin | 2021-01-26 18:04

first time it shoots towards the player but it keeps shooting in that direction after the first time.

mdubaisi | 2021-01-26 18:37

Do you create a new bullet every time or do you just reuse the same one over and over again? Because the ready function which sets the direction the bullet is traveling is only automatically called once.

exuin | 2021-01-26 18:48

I create a new one every time.

mdubaisi | 2021-01-26 18:50

So you want the bullet to follow the player instead of going in a straight line?

exuin | 2021-01-26 19:42

yeah, btw thanks for you precious time.

mdubaisi | 2021-01-27 05:19

:bust_in_silhouette: Reply From: psear

The variable target_pos is only set once, under _ready, it’s not getting updates with the players position. You need to regularly update the target position with the player’s position otherwise the bullet will just go towards the place you set it.

You could try moving the code from _ready() into your _physics_process().

thanks, it works now.

mdubaisi | 2021-01-27 05:19