- Home /
Enemy Shoots At Player When A Certain Distance
Alright, so I've been working on a top down space shooter with Javascript for a few weeks, and recently I've been trying to make my enemy prefab shoot at the player when he's on screen. I've been trying to calculate distance between the two with a Vector.3 and I've tried using sqr.magnitude. I've had no luck, having either: A) Every enemy on screen performs the function EnemyShoot() at the regular intervals, but they start doing it from the start of the scene (regardless of the distance between the individual and the player) B) The enemy performs the function, but does it every frame (even though I have an Instantiate there to make the shooting function happen every 1.3 seconds. The enemy doesn't even wait to be a certain distance from the player, it just does it when it's a certain distance from where the player STARTED at C) Absolutely nothing happens.
This worked perfectly! Thanks so much. I used a cube rather than a sphere due to level design choices, though. Thanks again!
Answer by dkNinja · Apr 13, 2012 at 05:25 PM
In order to make the enemy shoot, when a certain distance from the player, try adding a rigidbody to the player and a sphere trigger to the enemy. The radius of the trigger would be the distance at which the enemy starts to shoot. So, when the enemy is radius distance from the player, the trigger fires the OnTriggerEnter event http://unity3d.com/support/documentation/ScriptReference/Collider.OnTriggerEnter.html. You can start a coroutine to fire at a certain interval. When the enemy gets too far away, OnTriggerExit fires and you can stop the coroutine.