Instance multiple KinematicBodies2D with DIFFERENT moving vectors.

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

Hello there! Hope everyone is doing good.

I am working on an Endless mobile space game. I am trying now to implement a system that spawns asteroids with a RANDOM speed and a RANDOM moving vector. This is the script I came up with:

func spawn_asteroids():
	if Input.is_action_just_pressed("F"):
		
		# The center of the circle on which the Asteroids spawn
		var sphereCenter = viewport / 2
		# Now to spawning the asteroids
		for i in range(asteroidsCount):
			var spawn_pos = sphereCenter + sphereRadius.rotated(deg2rad(randi() % 360))
			var asteroidInstance = asteroid.instance()
			asteroidInstance.position = spawn_pos
			# Randomly scale the asteroid
			var scaleXY = rand_range(1, 3)
			asteroidInstance.scale = Vector2(scaleXY, scaleXY)
			add_child(asteroidInstance)
			# Here I choose the destination of the asteroid which is a RANDOM point from WITHIN my game's viewport.
			var destination = Vector2((rand_range(100, viewport.x - 100)), (rand_range(100, viewport.y - 100)))
			# I connect and emit these information to my Asteroid scene
			self.connect("movingVector", asteroidInstance, 'move_towards_vector')
			emit_signal('movingVector', spawn_pos, destination)

This is the code for my asteroid:

func _process(delta):
	move_and_slide(motion)

func move_towards_vector(spawn_pos, destination):
	var asteroidSpeed = rand_range(min_speed, max_speed)
	motion = (destination - spawn_pos).normalized()  * asteroidSpeed

The problem about the code I am currently using is that, If I spawn multiple Asteroids, They all adapt the same speed and the same move vector which is not ideal. How can I make it that every single instance has its OWN values and not get affected by other asteroids’

Hope I made sense. Have a good one and Thanks in advance.

:bust_in_silhouette: Reply From: Inces

There was no point to use signalling here. All of Your asteroids are connected to the same signal, so whenever new asteroid is created, they all change direction accoring to new signal. It would be so much easier if You just arbitrary forced random vector upon asteroid when instantiating it. Remove connections and signals and just brutally, directly call asteroidInstance.move_towards_vector(spawn_pos,destination). Good example of overengineered code :slight_smile:

Highly appreciated! Indeed very overengineered code that I am writing… It’s always the small stuff that I don’t take into consideration.

JCNegar | 2022-04-11 22:53