How to make an enemy shoot at the player?

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

Current bullet spawning/aiming code I have that doesn’t work correctly.

func _on_fire_rate_timeout():
for i in [spawner]:
	var bullet = pl_enemy_bullet.instance()
	get_tree().root.add_child(bullet)
	bullet.position = i.global_position 
	bullet.rotation = i.global_rotation 
	
	var direction = (player.global_position - global_position).normalized() 
	i.global_rotation = direction.angle() + PI / 2.0
	bullet.global_rotation = direction

When you say it doesnt work properly what do you mean?

Gluon | 2022-12-26 11:13

Sorry, I should have specified.

Instead of aiming at the player it aims opposite of the players position

wolvertox | 2022-12-28 01:46

:bust_in_silhouette: Reply From: scopericrit

I assumed the problem is that your spawner and the bullets won’t look at the player when it shoots

func _on_fire_rate_timeout():
for i in [spawner]:
    var bullet = pl_enemy_bullet.instance() 

    # another way of adding bullets to the scene tree
    var main_scene = get_tree.current_scene
    main_scene.add_child(bullet)

    bullet.position = i.global_position 
    bullet.rotation_degrees = i.rotation_degrees

    var direction = (player.global_position - global_position).normalized() 
    # if the spawner is in top down and you want the spawner to look at the player
    i.look_at(player.global_position)
    # the spawner will add pi divided by 2 amount of rotation
    i.rotation += PI / 2
    # I assumed that your bullet will have direction.angle() instead of just direction since it will compare a float with a Vector2, making it invalid
    bullet.look_at(player.global_position) 

Thank you, but it still gives me the same issue I had before where instead it aimed in the opposite direction of the players position.

wolvertox | 2022-12-28 02:04

:bust_in_silhouette: Reply From: Gluon

If it aims in the opposite of the players direction couldnt you just do this

func _on_fire_rate_timeout():
for i in [spawner]:
    var bullet = pl_enemy_bullet.instance()
    get_tree().root.add_child(bullet)
    bullet.position = i.global_position 
    bullet.rotation = i.global_rotation 

    var direction = (player.global_position - global_position).normalized() 
    i.global_rotation = direction.angle() + PI / 2.0
    bullet.global_rotation = direction - 180

I tried that but It gives me the error “Invalid operands ‘Vector2’ and ‘int’ in operator ‘-’.”

wolvertox | 2022-12-28 19:43

Okay have you tried reversing the original direction settings then?

var direction = ( global_position - player.global_position).normalized() 

Gluon | 2022-12-28 19:51

It worked, thank you.

wolvertox | 2022-12-30 18:28

Its the simple things! Glad it worked for you good luck with your game.

Gluon | 2022-12-30 18:34