Instance is on wrong position

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

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

1 Like
:bust_in_silhouette: Reply From: DaddyMonster

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!