0 votes

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)

Godot version latest version as of January 7th 2022
in Engine by (14 points)

1 Answer

0 votes

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.

by (2,087 points)
Welcome to Godot Engine Q&A, where you can ask questions and receive answers from other members of the community.

Please make sure to read Frequently asked questions and How to use this Q&A? before posting your first questions.
Social login is currently unavailable. If you've previously logged in with a Facebook or GitHub account, use the I forgot my password link in the login box to set a password for your account. If you still can't access your account, send an email to [email protected] with your username.