Topic was automatically imported from the old Question2Answer platform.
Asked By
ashtina3
i need it to spawn randomly after i press a key
(if you were to spawn it an infinite number of times it would form a circle with a radius of 137 pixels)
The trick is to add the obj, rotate it by a random amount (so between zero and two PI radians [360 degrees]) and then march it forward in the direction it’s facing. You can get the direction by getting the transform basis unit vector and scaling it by the distance you want move it.
I’m assuming you know how to bind a key, if not just ask.
var kinematic_start_position = Vector2(300, 300)
var offset = 137
var kinematic_scene = preload("path_to_scene_goes_here")
var rng = RandomNumberGenerator.new()
func _input(event):
if event.is_action_pressed("spawn_kinematic"):
var rot = rng.randf_range(0, 2*PI)
var kinematic = kinematic_scene.instance()
add_child(kinematic)
kinematic.global_position = kinematic_start_position
kinematic.rotate(rot)
kinematic.global_position += kinematic.transform.y * offset
nb. this code was written very quickly and not checked so it’s likely there’s a silly mistake. Verboseness for clarity.