How to Transform an Instance's Position Programatically

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

So I have a scene (Node2D) called spr_tile and another scene (Node2D) called r_level01.

In spr_tile, I have a GDscript that draw a 32 x 32 rectangle.

Meanwhile, in r_level01, I want to generate children of spr_tile. My goal is to create 4 spr_tile side by side → (0,0), (0,32), (32,32), (32,32). But I can’t find out on how to change the position of the instance.

Here is what I have tried:

onready var tile_spr = preload("res://spr_tile.tscn");

func _ready():
	var tile_ins = tile_spr.instance();
	var tile_ins2 = tile_spr.instance();
	var tile_ins3 = tile_spr.instance();
	var tile_ins4 = tile_spr.instance();
	
	# tried to change the position
	tile_ins.set_position(Vector2D(0,0)); #is not working
	tile_ins1.set_position(Vector2D(0,32)); #is not working
	tile_ins2.set_position(Vector2D(32,0)); #is not working
	tile_ins3.set_position(Vector2D(32,32)); #is not working

	add_child(tile_ins);
	add_child(tile_ins2);
	add_child(tile_ins3);
	add_child(tile_ins4);

Wwhat do I do wrong?

:bust_in_silhouette: Reply From: jgodfrey

What you have is basically correct, though you have at least a few typos that would prevent it from working.

Here’s a minimally edited version that uses the standard godot icon.png file in the instanced scene…

Note that you can also set the position property directly via tile_ins.position = Vector2(0,0)

extends Node2D

onready var tile_spr = preload("res://sprite.tscn");

func _ready():
	var tile_ins = tile_spr.instance();
	var tile_ins2 = tile_spr.instance();
	var tile_ins3 = tile_spr.instance();
	var tile_ins4 = tile_spr.instance();

	# tried to change the position
	tile_ins.set_position(Vector2(0,0)); 
	tile_ins2.set_position(Vector2(0,64)); 
	tile_ins3.set_position(Vector2(64,0));
	tile_ins4.set_position(Vector2(64,64)); 

	add_child(tile_ins);
	add_child(tile_ins2);
	add_child(tile_ins3);
	add_child(tile_ins4);