0 votes

When I press fire key during jumping,
the bullet is instantiated on the air and moving forward for a bit,
but then it goes down.

How can I fix this?

player code

extends KinematicBody2D

func fire():
    var projectile = load("res://Projectile.tscn")
    var bullet = projectile.instance()
    add_child_below_node(get_tree().get_root().get_node("Stage"), bullet)

bullet code

extends KinematicBody2D

    var velocity = Vector2()
    const SPEED = 2500

    func _ready():
        velocity.x = SPEED

    func _physics_process(delta):
        if position.x > SPEED / 2:
            queue_free()
        move_and_slide(velocity)
Godot version 3.2.3
in Engine by (14 points)

Honestly the code you have already doesn't look like it would cause the bullet to go down since there is no vertical velocity at all. Maybe something else is going on?

I found out the problem is the bullet position wasn't set properly.
So I tried to change code like below and it works now :)
Thank you for comment!

player

func fire():
    var bullet = preload("res://Bullet.tscn").instance()
    if $Sprite.flip_h:
        bullet.direction = -1
        $Muzzle.position.x = -14
        bullet.global_position = $Muzzle.global_position
    else:
        bullet.direction = 1
        $Muzzle.position.x = 14
        bullet.global_position = $Muzzle.global_position
    get_tree().get_root().get_node("Stage").add_child(bullet)

bullet

func _physics_process(delta):
    if direction == 1:
        move_and_slide(velocity)
        if position.x > SPEED * direction / 2:
            queue_free()
    else:
        move_and_slide(velocity)
        if position.x < SPEED * direction / 2:
            queue_free()

Please log in or register to answer this question.

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 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 webmaster@godotengine.org with your username.