How to spawn enimies in a given area

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

I am trying to get an area and spawn enimies within. I think my code should work the only problem I have is that the varibles high and low are obviously not interger’s so I can’t get a random number from it or use it as a position, if anyone could help me fix that or make a better way to spawn enimies would be very helpful.

#when player enters the area
func _on_Area2D_body_entered(body):
	$Camera2D.current = true #the camarea switches to the one the player is in
	var center = $Area2D/CollisionShape2D.position
	var width = $Area2D/CollisionShape2D.shape.extents
	var high = center + width 
	var low = center - width 
	num = randi()%7+1 #picks a number between 1-7
	for i in range(num): # spwans in num eniemies
		# spawns enimies in the range of the area
		enemy_instance.position.x = randi()%high+low
		enemy_instance.position.y = randi()%low+high

A) round high and low to get integers?
B) use functions to get random eg. with rand_range

Reloecc | 2020-09-15 18:24

do you mean like this:

	enemy_instance.position.x = rand_range(high, low)
	enemy_instance.position.y = rand_range(low, high)

because I still get this error: Invalid type in built-in function ‘rand_range’. Cannot convert argument 1 from Vector2 to float.

swordofbling | 2020-09-15 18:32

So fix it instead of writing here :wink: center is Vector2, so high and low are too…
Correct it by:

var x_high: float = center.x + width 
var x_low: float = center.x - width 
var y_high: float = center.y + width 
var y_low: float = center.y - width 

Reloecc | 2020-09-15 18:36

Thank you so much I started to get the error Invalid operands ‘float’ and ‘Vector2’ in operator ‘+’. so I mannuly set the width value as for some reason it doesn’t like to add them together at it worked

swordofbling | 2020-09-15 19:37

:bust_in_silhouette: Reply From: swordofbling

Thank you to Reloecc for answering the question

Use the Comment button to reply, not an answer :slight_smile:

Calinou | 2020-09-15 22:40