0 votes

I have laser scene every time I touch the screen a new copy of it is created. It should be exactly where my position2d node is but sometimes it's not. I have 2 scripts.

This script is attached to Main node

 var laser_scene = preload("res://Scenes/Laser.tscn")
onready var laser_pos2d = $LaserPosition
var laser_instance

func _unhandled_input(event):
    if event is InputEventScreenTouch:
            var touch_position = event.get_position()
            laser_instance = laser_scene.instance()
            laser_instance.set_position(laser_pos2d.get_global_position())
            add_child(laser_instance)

2nd Script is attached to my laser/bullet

func _process(delta):
    var direction = (touch_position - get_position()).normalized()
    position += direction * speed
    distance_check()

if I use the code from process function the laser is always at the position of it's parent Main instead of position2d node. I don't know how to fix it

Godot version 3.4.4
in Engine by (12 points)

1 Answer

0 votes

Add the child and then set its position, not vice versa, it doesn't make sense to set the position of something that's not in the scene. Also, set it in global space in case you adjust the parent's transform:

Like this:

func _unhandled_input(event):
    if event is InputEventScreenTouch:
        var touch_position = event.get_position()
        laser_instance = laser_scene.instance()
        add_child(laser_instance)
        laser_instance.set_global_position(laser_pos2d.get_global_position())

See if that works, fingers crossed!

by (2,156 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 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.