When I spawn 2 different instances with random vectors they seem to share the same vector when run in the browser

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

I am very new to Godot and generally making games but I have this tiny problem.

I am making an Asteroids type game and the basics of it are. I destroy an Asteroid and it splits into multiple smaller versions with random vectors.

This works perfectly fine until I try to run it in a browser. In the browser, the vectors for each separate instance are exactly the same every single time.

Here is my code for spawning them

var ma = med_asteroid.instance()
var ma2 = med_asteroid.instance()
ma.spawn(position)
ma2.spawn(position)
get_parent().call_deferred("add_child", ma)
get_parent().call_deferred("add_child", ma2)

Here is the spawn code

func spawn(pos):
	var rng = RandomNumberGenerator.new()
	rng.randomize()
	
	position = pos
	rotation = rng.randf_range(PI,-PI)
	speed = rng.randi_range(ba_speed_min, ba_speed_max)
	
	velocity = Vector2(speed, 0).rotated(rotation)

Thank you.

Are the position and rotation variables local to the spawn() function? Or are they globally accessible?

Ertain | 2020-04-01 18:06

They come along with KinematicBody2D I believe, They are not variables I have created. They are different per instance of the object.

I do not know godot that well but I think they are from the Node2D transforms.

sadfacerl | 2020-04-01 18:13

:bust_in_silhouette: Reply From: lufemas

Try to add a parameter on spawn function like:

   func spawn(pos, count):
    var rng = RandomNumberGenerator.new() * count

Create a count var or take it from anywhere just to be sure that the browser do not create the same number on the randomizer. Javascript is no a Top-Down language, everything is running together, that may be causing this.
Or if you are hard coding the spawns, just do like:

ma.spawn(position,1)
ma2.spawn(position,2)

You need to correct the final number maybe, I dont know how everything is working on your code, but try to add something different for each spawn.

Awesome, you are onto the right Idea.

I got an error from using

func spawn(pos, count):
    var rng = RandomNumberGenerator.new() * count

However, if I do use the count idea here.

 rotation = rng.randf_range(PI,-PI) * count

It seems to work now, thank you.

sadfacerl | 2020-04-01 19:38

Great! I’m happy to help.

lufemas | 2020-04-01 20:13