Instances are spawning relative to the center of my screen (2D)

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By Jambers
:warning: Old Version Published before Godot 3 was released.

I am trying to spawn an object “yellow_sprite” at the location (0,0) when I press a button “yellow_spawn_button”. Instead of spawning at (0,0), the object is spawning on top of its parent.

Code:

extends Node2D

var yellow_sprite = preload("yellow_sprite.tscn")
var yellow_sprite_location = Vector2(0,0)

func _on_button_pressed(): "Spawn a yellow pixel when the yellow button is pressed"
	var yellow_sprite_create = yellow_sprite.instance()
	yellow_sprite_location=Vector2(0,0)
	yellow_sprite_create.set_pos(yellow_sprite_location)
	get_node("pixel").add_child(yellow_sprite_create)
	
func _ready():
	get_node("yellow_spawn_button").connect("pressed",self,"_on_button_pressed")
:bust_in_silhouette: Reply From: timoschwarzer

Use yellowspritecreate.set_global_pos(yellowspritelocation) instead of yellowspritecreate.set_pos(yellowspritelocation).

And please use the code button when pasting code here :wink:

Thanks for the response!

I have made the suggested replacement, but the yellow pixel still spawns on top of its parent.

Jambers | 2017-07-03 11:28

Try to add the node to its parent first and then use set_global_pos to set its position.

timoschwarzer | 2017-07-03 12:05

Perfect, it’s working like a charm!

Jambers | 2017-07-03 13:34