- Home /
Enemies spawning on player and rotated
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
}
}
Thanks for any help you can offer.
For the first problem, when you drag the prefab of the ghost into the scene, is it right side up?
no it is in the same position as when one is spawned. if I rotate the prefab, the clones do not retain the rotation
im still new to Unity but it sounds like you are forgetting to hit the Apply button at the top of the inspector to save the changes made to the prefab?
Answer by VioKyma · Aug 02, 2013 at 06:01 AM
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.
Your answer
Follow this Question
Related Questions
Kill the Player? 1 Answer
How to stop enemy within certain distance of player? 2 Answers
How to make Enemy on scary game ? 1 Answer
Player lives script 1 Answer