–1 vote

I made a game where the bullets spawn from a spaceship and travel towards the mouse, so far so good beside this problem where the bullets instead of spawning only from the spaceship spawn also from where the parent of the bullets is, which in this case is "world".
I tried writing a piece of code where the bullets position gets updated the moment they spawn but nothing worked, and when removing it completely it stops spawning in both directions.

Here is my player(spaceship) code:

extends KinematicBody2D

export var speed = 1
const Bullet_load = preload("res://bullet.tscn")
const RELOAD_TIME = 0.1
var reloading = 0.0
var velocity = Vector2()

func get_input():
    speed = 100
    velocity = Vector2()
    if Input.is_key_pressed(KEY_D):
        velocity.x += 1
    if Input.is_key_pressed(KEY_Q):
        velocity.x += -1
    if Input.is_key_pressed(KEY_S):
        velocity.y += 1
    if Input.is_key_pressed(KEY_Z):
        velocity.y += -1
    velocity = velocity.normalized() * speed


func _physics_process(delta):
    look_at(get_global_mouse_position())
    get_input()
    if Input.is_key_pressed(KEY_SPACE):
        if reloading <= 0.0:
            reloading = RELOAD_TIME
            var bullet = Bullet_load.instance()
            get_parent().add_child(bullet)
            bullet.position = position
            bullet.direction=(get_global_mouse_position()-global_position).normalized()
            reloading = RELOAD_TIME
    reloading -= delta
    velocity = move_and_slide(velocity)

And the code for the bullet:

extends KinematicBody2D

var velocity = Vector2.ZERO
var speed = 200
var direction= Vector2.ZERO

func _physics_process(delta):
    velocity =  direction * speed
    if not get_node("notifier").is_on_screen():
        queue_free()

    move_and_collide(velocity * delta)
asked Jun 1 in Engine by senkai (13 points)
retagged Jun 1 by senkai

the bullets [...] spawn also from where the parent of the bullets is

I cannot reproduce this. Your code works fine for me.

Can you provide an example project with the issue?

1 Answer

0 votes

Hi,
I've tried your code and I think it works as it should.
The bullets spawn in the world as you have the code get_parent().add_child(bullet)

When I press that space bar I get a stream of bullets that go to the mouse position and as I move the mouse I get this effect:

Is this not the effect you want

answered Jun 1 by deaton64 (1,205 points)
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.