How to get a Int value for a sprites X & Y Position

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By 10xyz
extends Node2D
var tree = preload("res://Objects/Tree.tscn")
var randomX = (randi() % 5561 + -2253)
var randomY = (randi() % 4395 + -1821)

func _spawn_tree():
	var Tree = tree.instance()
	Tree.global_position = ???

This is a Tree Spawner. I have 2 values, randomX and randomY
I want to set the position of “Tree” using these 2 values. How can I do this?

Note: Tree is already the name of a class in Godot, so your variable is conflicting with it (maybe not an error in your case tho).

Here are some suggestions to improve the code:

extends Node2D

# Use uppercase name suffixed with `Scene` so it is clear it is a scene,
# and `const` can be used because `preload` is run when the script is
# parsed, not when *instances of the script* are run.
# it also prevents it from being accidentally modified.
const TreeScene = preload("res://Objects/Tree.tscn")

var randomX = (randi() % 5561 + -2253)
var randomY = (randi() % 4395 + -1821)

func _spawn_tree():
    # Rename variable to match more standard naming convention
    # and avoid ambiguity with existing class name
    var tree = TreeScene.instance()
    tree.global_position = Vector2(randomX, randomY)

Zylann | 2022-02-23 14:01

:bust_in_silhouette: Reply From: rakkarage
Tree.global_position = Vector2(randomX, randomY)