My bullet follows the direction of my mouse in mid-air

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

As the title states, My bullet follows the direction of my mouse, I’ll provide the code I used.

Bullet code: (This handles in which direction and how fast my bullet will go)

func _physics_process(delta):
	var direction = get_tree().root.get_child(0).get_node("Player").direction()
	velocity = SPEED*delta*direction
	
	$AnimatedSprite.rotation_degrees = get_tree().root.get_child(0).get_node("Player").get_child(1).get_child(4).rotation_degrees
	translate(velocity)

Hand code: (This handles the rotation of the player’s hand including the gun)

func _process(delta):
	
	var mpos = get_global_mouse_position()
	look_at(mpos)

	if rotation_degrees <= -90:
		rotation_degrees = -90
	elif rotation_degrees >= 90:
		rotation_degrees = 90

Bullet spawn code: (I think this is where the problem lies, as it handles where the bullet will spawn)

func _process(delta):
    if Input.is_action_pressed("Shoot"):
    		shoot()
func shoot():
	if $Cooldown.is_stopped():
		var bullet = BULLET.instance()
		get_tree().root.get_node("Stage").add_child(bullet)
		bullet.global_position = $Body/Sprite/Position2D.global_position
		$Cooldown.start()
	
func direction():
	var direction = (get_global_mouse_position() - $Body/Sprite/Position2D.global_position).normalized()
	return direction

here's what's happening

what is the direction function on the bullet script for?

Millard | 2020-05-28 02:40

Just to clarify, the bullet spawn is in the player script, it may cause some confusion, I should’ve stated it more clearly. The direction tells the bullet to shoot in that direction as seen here:

velocity = SPEED*delta*direction

any thoughts?

Faun | 2020-05-28 03:54

Should the velocity of the bullet ever change in speed or direction over time?

RedBlueCarrots | 2020-05-28 04:15

:bust_in_silhouette: Reply From: RedBlueCarrots

I think your issue is that you are calling the direction() function every frame. In order to fix this, create another variable to store the value direction() gives when the bullet is spawned, and re-use that instead of re-calculating

Thank you for your help! :slight_smile:

Faun | 2020-05-28 05:21