How to prevent the bullet is moving down when I shot during jumping?

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

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)

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?

exuin | 2021-05-17 22:39

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 :slight_smile:
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()

bellhwi | 2021-05-18 04:03