[SOLVED] Is there a better way to detect player within range?

Started by
1 comment, last by Aspirer 10 years, 5 months ago

In my game, I have various doorways that act as spawn points for enemies. I'm trying to limit the spawners to only spawning when the player is determined to be within 10 meters of the spawn point (I'm only assuming this is the standard way enemies are randomly spawned in the majority of games... Having never done this before, this is the first way that came to my mind: Looping through each degree of a full 360* circle, determine all colliders within range (in my case, 10 meters) and if one of them is the enemy, spawn an enemy; if not, finish the circle, wait one second and repeat.

The following is my code for this. (With extra commenting just to make it beyond plainly obvious what each line is for, lol) This does have the basic functionality I'm looking for, but since I haven't done it before, I'm curious if this is the best or most efficient way to do what I'm trying to do.

Thanks for the help!


public IEnumerator SpawnAnEnemy() {     
	while(Player.amIAlive) {
          	if (EnemyCount < MaxEnemies){
			for (float degree = 0; degree <= 360; degree++){	
				angleToV3Conversion = new Vector3(Mathf.Sin(Mathf.Deg2Rad * degree), 0, Mathf.Cos(Mathf.Deg2Rad * degree));	//CONVERT DEGREE TO A POINT IN 3D SPACE
				rayCastHitInfo = Physics.RaycastAll (transform.position, angleToV3Conversion, 10F);                    //PLOT RAY AT SPECIFIC ANGLE, RETURN ALL HITS IN THAT DIRECTION
				for (int hitNumber = 0; (hitNumber < rayCastHitInfo.Length); hitNumber++){                         //LOOP THROUGH EACH RETURNED HIT
					if (rayCastHitInfo[hitNumber].collider.gameObject.tag == "Player"){              //IF RETURNED HIT WAS PLAYER
						Instantiate (enemy, new Vector3(spawnX, spawnY, spawnZ), new Quaternion(spawnXRot, spawnYRot, spawnZRot, 0));       //SPAWN ENEMY AT SPECIFIED LOCATION
						EnemySpawner.EnemyCount++;		
						yield return new WaitForSeconds(1F);	//EXIT LOOP FOR ONE SECOND
      					}
				}
			}
		}
		yield return new WaitForSeconds(1F);  
	} 
}//If enemy count is less than maximum & Player in range, spawn enemy, increment count, and wait 1 second--repeat.
Advertisement
That's... creative, I suppose, but terribly inefficient. If you know the positions of the enemies (and you should), you can reduce the number of rays you need to trace by determining the angle at which enemies exist. Even simpler, you can find the Euclidean distance between the spawn point and the enemy, without needing a ray cast:

for each enemy:
    if sum(square(enemy_position - spawn_position)) < 10*10 then
        enemy is within spawn range

Wasn't checking for enemy range, was determining if the player was in range. But, I see what you're doing, and agree... I assumed it would be more difficult and just over-thought the whole process.

Thanks for the smack in my face. ^_^

This topic is closed to new replies.

Advertisement