- Home /
Enemy spawn script/player position(java/js)
I am working on an enemy spawn script that needs some adjustments/polishing. I want to make zombies spawn in front of my "guy/player". After they spawn in front of him, I know how to do the rest. Just the spawning in front part is the only thing I am confused on. I was using a Invoke repeating() to make zombies spawn at a certain spot but now I want them to span directly in front of my player.I know that I will have to get my "players" position but I don't know what to do from there. Thanks for the help and your time.(feel free to rewrite my code or make any helpful adjustments)
here is my code:
var SpawnObject : GameObject;
var player : Transform;
private var SpawnStartDelay : float = 0;
var SpawnRate : float = 1.0;
private var amountOfE : float = 0;
var maxAmount : float = 10;
var distance = 15;
var playerCloseEnough = false;
function Start()
{
InvokeRepeating("Spawn", SpawnStartDelay, SpawnRate);
}
// Spawn the SpawnObject
function Spawn()
{
if(playerCloseEnough == true)
{
amountOfE++;
Instantiate(SpawnObject, transform.position, transform.rotation);
}
else{}
}
function Update()
{
if(amountOfE == maxAmount)
{
CancelInvoke("Spawn");
Destroy(this.gameObject);
}
else{}
if(Vector3.Distance(transform.position, player.position) < distance)
{
playerCloseEnough = true;
}
}
Answer by S_Darkwell · Mar 08, 2015 at 03:33 AM
Try replacing:
Instantiate(SpawnObject, transform.position, transform.rotation);
With:
Instantiate(SpawnObject, transform.position + (transform.forward * 2.0f), transform.rotation);
Replace "2.0f" with the distance you want them to be spawned in front of the player.
Alternatively, you can use:
Instantiate(SpawnObject, transform.position + transform.TransformVector( 0f, 0.5f, 2.0f ), transform.rotation);
Replace with "0f, 0.5f, 2.0f" with either x,y,z floats or a Vector3 representing the position you wish to spawn the enemy in relation to the direction that the player is facing.
Hope that helps!
As I wrote it, it would have to be applied to the player script.
If you wanted to add it to the enemy script ins$$anonymous$$d, you would have to retrieve the player's transform first, then apply this code.
.TransformVector(#,#,#) applies to whatever transform precedes it. For example, if you had a variable named PlayerChar in your enemy script that contained your player's GameObject, you could call:
PlayerChar.transform.position + PlayerChar.transform.TransformVector( 0f, 0.5f, 2.0f );