proximity spawn point only on X Z axis

I'm making a script to spawn some baddies

currently I'm using

var distanceToPlayer = Vector3.Distance(transform.position, targetplayer.position);

and when distance to player is smaller than my spawnrange instantiate the bad guys all OK.

however it is checking the distance in all direction,

I'm using it in a scene in a multi story carpark (lots of floors ontop of each other) and when I am on the floor below I'm triggering the spawns point on the floor above.

So can anyone help I need to check the distance but only on the X + Z axis (on a horizontal plane not vertically)

3 Answers

3

It sounds like what you're wanting is for the entities to spawn only on the same level that the player is on, correct?

If so, you can check the Y distance and the XZ distance separately. The Y distance is simply:

float yDistance = Mathf.Abs(transform.position.y - targetPlayer.position.y);

The XZ distance can be computed as follows:

Vector3 targetPosition = targetPlayer.position;
targetPosition.y = transform.position.y;
float xzDistance = Vector3.Distance(transform.position, targetPosition);

You can then check the distances independently using appropriate thresholds to see if an entity should be spawned.

cheers got me on the right track I went with this in the end if its of use to anyone

var distanceToPlayer = Vector3.Distance(transform.position, targetplayer.position);

var targetDir = targetplayer.transform.position - transform.position;

if (distanceToPlayer < spawnRange && oneTimeRespawn == true) {

var yDistance = transform.position.y - targetplayer.position.y; if (yDistance < 0.5) {

//spawn bad guys }

I probably wouldn't calculate the distance to the player every frame, it'd probably be more efficient to give the spawnpoint a sphere collider, and flatter the collider so its more of a flat circle. Then just use OnTriggerEnter() and OnTriggerExit() to detect the player.

If you are dead set on calculating the distance, I would use the square magnitude instead, as it is much less resource-intensive.