0 votes
onready var velo = set_linear_velocity(Vector2(rand_range(250, -250),rand_range(250, -250)))

This is my code for the randomized direction i use for my Rigidbody2D, because everytime the Rigidbody2D goes in a different direction with this code but the only issue i have with that is that the speed is different . I want it to be constantly one speed, like 250, and not inbetween 250 and -250.

in Engine by (137 points)

1 Answer

+2 votes
Best answer

The speed is determined by the length of the vector. So you can either normalize this length and multiply with 250:

onready var velo = set_linear_velocity(Vector2(rand_range(250, -250),rand_range(250, -250)).normalized() * 250)

Or you can simply use a randomly rotated Vector with length 250:

onready var velo = set_linear_velocity(Vector2(250,0).rotated(randf() * 2.0 * PI))
by (1,758 points)
selected by
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.