Pick z = randf_range(-1, 1) and a = randf_range(0, TAU), then use Vector3(r * cos(a), r * sin(a), z) with r = sqrt(1 - z * z). That covers the sphere evenly. In our Godot 4.7 test of 100,000 directions, Vector3(randf_range(-1, 1), randf_range(-1, 1), randf_range(-1, 1)).normalized() put 35.8% within 20 degrees of the 8 corners of a cube, where an even spread gives 24.1%. A random yaw and pitch put 22.1% within 20 degrees of straight up or down instead of 6.0%. The even height and angle gave 24.2% and 6.1%.
The code
Save it as random_dir.gd. on_sphere() gives a direction anywhere, in_cone() one within max_angle_deg of a forward direction, for a fountain, a spray or shotgun pellets. Multiply the result by a speed to launch debris or sparks, and pass your own RandomNumberGenerator to repeat a seed.
extends RefCounted
## Random directions spread evenly over a whole sphere or inside a cone:
## firework bursts, flying debris, shotgun pellets.
static func on_sphere(rng: RandomNumberGenerator = null) -> Vector3:
var z := _rand(rng, -1.0, 1.0) # an even height gives an even spread over the surface
var a := _rand(rng, 0.0, TAU)
var r := sqrt(1.0 - z * z)
return Vector3(r * cos(a), r * sin(a), z)
static func in_cone(forward: Vector3, max_angle_deg: float, rng: RandomNumberGenerator = null) -> Vector3:
var z := _rand(rng, cos(deg_to_rad(max_angle_deg)), 1.0)
var a := _rand(rng, 0.0, TAU)
var r := sqrt(1.0 - z * z)
var f := forward.normalized()
var up := Vector3.UP if absf(f.y) < 0.99 else Vector3.RIGHT # looking_at() fails when up is parallel
return Basis.looking_at(-f, up) * Vector3(r * cos(a), r * sin(a), z) # +Z of this basis points along forward
static func _rand(rng: RandomNumberGenerator, from: float, to: float) -> float:
return rng.randf_range(from, to) if rng else randf_range(from, to)
What we measured
100,000 directions each way, from the same seed. Near means within 20 degrees. With an even spread that is 24.1% for the 8 corners of a cube, 18.1% for the 6 axis directions and 6.0% for straight up or down. Two runs gave the same numbers.
- Normalizing a random vector in a cube: 35.8% near the corners, 10.4% near the axes, 3.4% near up or down.
- A random yaw from 0 to 360 degrees and a random pitch from -90 to 90: 19.2% near the corners, 29.9% near the axes, 22.1% near up or down.
- The script: 24.2%, 18.0% and 6.1%. Throwing away vectors that fall outside the sphere before normalizing also worked: 24.2%, 18.1% and 6.1%.
- A 15 degree cone made from random yaw and pitch offsets of up to 15 degrees each: up to 21.05 degrees from the middle, out in the corners of a square, and 19.5% within 7.5 degrees. in_cone(): 15.00 degrees at most and 25.1% within 7.5, the even share.
- in_cone() pointing straight up: 10.00 degrees at most, with no error. The script switches the up vector for directions close to straight up or down.
- The same RandomNumberGenerator seed gave the same direction twice.
Why it happens
A cube reaches further out at its corners than a sphere, so a random point in it, pushed out to the sphere, ends up near a corner more often. Two random angles cover the sphere like lines of longitude, which all meet at the poles: each step of pitch gets the same share of directions, but near the top and bottom it covers much less of the surface. On a sphere every band of the same height has the same area, which is why an even height with an even angle around comes out even.
What to change
- A half sphere, for sparks that bounce off the ground: in_cone(Vector3.UP, 90.0).
- Points inside a flat circle instead of directions: a random point in a circle needs a square root. Rockets that burst into particles: fireworks without sub-emitters.
Bursts that are ready to play: Festival & Fireworks VFX for Godot 4 has rockets that burst by themselves, among them Peony, Willow Gold, Ring Cyan and Heart Pink, plus fountains, sparklers and confetti. One-shots start with play().
Tested in Godot 4.7 with the Compatibility renderer.
Ready-made: Festival & Fireworks VFX for Godot 4 has rockets that burst by themselves, Peony, Willow Gold, Ring Cyan and more, plus fountains and sparklers.
More how-tos for Festival & Fireworks VFX for Godot 4: Fireworks without sub-emitters · Confetti particles with random colors · Big particle effects that stay on screen
More how-tos: Game systems
- Hover a 3D object inside a SubViewport
- A turned building that covers the cells it stands on
- An inventory that never loses an item and never overfills a stack
- A JSON save that loads back exactly what you saved
- Fire that spreads one cell per step, in every direction
- A pooled enemy that comes back as fresh as a new one
- An enemy that stops at the dead player and finds the respawned one
- Poison, burn and bleed that keep ticking when applied again
- XP, qi and gold that keep growing without going negative
- Count slot line wins with wilds in front
- Count a lap only when the car really went round
- Make a seed repeat: daily runs, replays and roguelike seeds
- Offline progress that counts the time the game was closed
- A chance roll without the long bad-luck streaks
- Check crafting recipes in any order, with the right counts
- Make HP and mana regen the same at any frame rate
- Damage over time with the right number of ticks
- Spawn enemies where the camera cannot see them
- Keep a chasing horde from stacking into one enemy
- Make the fish bite after the same wait at any frame rate
- Snap buildings to the right grid cell on both sides of the origin
- Make a cooking timer fire once, on time
- Pick from a weighted loot table with the right chances
- Level up as many times as the XP covers
- Walk a patrol guard to each point without overshooting
- Remove items from an Array while checking them, without skipping any
- Scatter spikes, roots or trees in a circle without overlaps
- Count and take crafting items from every stack
- Play random sounds and events without obvious repeats
- Pick the growth image so the ripe one shows exactly when the crop can be picked
- Turn a day counter into season, day and year without a day 0
- An enemy that dies once, however many hits land
- A fair shuffle you can replay
- A ghost that drives the lap at real speed
- A vision cone that does not flicker at the edge
- Move a group of units without a pile-up
- A sprinkler that waters a round patch
- A slot reel that always lands forward on the result
- A crowd of NPCs that never emote or bob in step
- A song position that moves on every frame
- Nodes your editor tool adds that stay in the scene