How to set the position of a rigidBody via code?

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

Hi, I’m new at Godot, and I’m trying to set a function which create some thorns (rigidBody) randomly in a room in 3D.

As you can see in the code below, I’ve been trying it for a while. (the lines I commented are the ones i tried and didn’t work)

func spawn_thorn():
var pos_x = int(rand_range(-10,10))
var pos_z = int(rand_range(-10,10))
var Thorn = load("res://Done/Thorn.tscn")	
Thorn = Thorn.instance()
#Thorn.transform.origin(Vector3(pos_x, 5, pos_z))
#Thorn.set_global_transform(Vector3(pos_x, 5, pos_z))
#Thorn.set_global_translation(Vector3(pos_x, 5, pos_z))
#Thorn.position.x = pos_x
#Thorn.position.y = 5
#Thorn.position.z = pos_z
#Thorn.global_position = Vector3(pos_x, 5, pos_z)
#Thorn.set_global_position() = Vector3(pos_x, 5, pos_z)
#Thorn.set_global_position(Vector3(pos_x, 5, pos_z))
#Thorn.set_pos(Vector3(pos_x, 5, pos_z))
#var location = Vector3()
#location.x = pos_x
#location.y = 5
#location.z = pos_z
add_child(Thorn)

everytime I call this function, it would create a thorn. Their height would be the same (y = 5); but the position in the floor should be random, limited by the space in the room (x = rand_range(-10,10)) and (z = rand_range(-10,10))

Hi,
have tried to first add_child(Thorn). Since when you have no parent object you have no global_transform.

func spawn_thorn():
   var pos_x = int(rand_range(-10,10))
   var pos_z = int(rand_range(-10,10))
   var Thorn = load("res://Done/Thorn.tscn")   
   Thorn = Thorn.instance()
   add_child(Thorn)
   Thorn.global_transform.origin = Vector3(pos_x, 5, pos_z)

klaas | 2020-09-17 10:54

thank you so much :slight_smile:

Lcs-lts | 2020-09-17 12:20