I have a Spawn script that is working well except for two problems. I am attempting to spawn a ghost at a random position every few seconds. This part is working, but unfortunately it spawns them on their backs instead of right side up. I need them to rotate 90 degrees on the X axis and a cant figure out how to do it. Second sometimes the ghosts spawn on top of the player or very close. My goal is for them to not spawn unless they are a certain distance from my player.
Here is my code:
#pragma strict
function Start(){
yield WaitForSeconds(5);
InvokeRepeating("Spawn",0.01f,3.0f);
}
var enemyPrefab: Rigidbody;
function Spawn(){
for (var i = 0; i < Random.Range(1, 4); i++){
var Pos = Vector3(Random.Range(-18,18), 2.3, Random.Range(-18, 18));//Where to spawn enemies
var newEnemy: Rigidbody = Instantiate(enemyPrefab, Pos, Quaternion.identity);//Spawn
newEnemy.tag = "ghost";//Tag the new enemy
}
}
For the spawn distance, I would do something like having a spawn distance variable to determine the distance from the player. You will also need the location of the player (obviously).
Then you will need to compare the pos variable with the player location before spawning.
var spawnDistance = 5.0;
var playerX = Player.transform.position.x;
var playerZ = Player.transform.position.z;
if ((pos.x < playerX - spawnDistance || pos.x > playerX + spawnDistance)
&& (pos.z < playerZ - spawnDistance || pos.z > playerZ + spawnDistance))
// set the pos
else
// set some position that is appropriate
In this way, you can spawn an enemy so long as it’s not within the specified range. And handle the case that it is by adjusting the pos vector.
For the rotation, you should be able to set LookAt() for the object after instantiating.
newEnemy.tag = "ghost";//Tag the new enemy
Vector3 myVector = new Vector3(x, y, z);
newEnemy.transform.LookAt(myVector);
where x, y and z are the direction you are wanting it to face.
Hope this helps, let me know if you have any questions.