0 votes

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

in Engine by (15 points)

what is the direction function on the bullet script for?

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?

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

1 Answer

+2 votes
Best answer

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

by (399 points)
selected by

Thank you for your help! :)

Welcome to Godot Engine Q&A, where you can ask questions and receive answers from other members of the community.

Please make sure to read Frequently asked questions and How to use this Q&A? before posting your first questions.
Social login is currently unavailable. If you've previously logged in with a Facebook or GitHub account, use the I forgot my password link in the login box to set a password for your account. If you still can't access your account, send an email to [email protected] with your username.