- Home /
Making a Turret Have a Circle Sector Range
In the game I'm developing, a turret has a range shaped like a sector of a circle. The turret has an initial forward vector, and what I need is to have the turret only target enemies within 54 degrees (On the XZ plane) of that forward vector. The y axis is irrelevant here. How can I do this?
Answer by aldonaletto · Jun 18, 2013 at 12:30 AM
If you know the enemy positions, you can compare the direction vector turret->enemy to the initial forward vector. Supposing that forwardDir has the initial forward direction, you can use a function like this (turret script):
function EnemyInRange(enemy: Transform): boolean {
// get direction vector:
var dir: Vector3 = enemy.position - transform.position;
dir.y = 0; // make it strictly horizontal
forwardDir.y = 0; // make forwardDir stricly horizontal too
// return false if outside angle...
if (Vector3.Angle(dir, forwardDir) > 54) return false; // check angle...
// or out of range
if (Vector3.Distance(enemy.position, transform.position) > range) return false;
// otherwise return true
return true;
}
HINT: A simple way to keep all enemies in a fast and always updated array is to child them to an empty object: create the empty object, call it Enemies and reset its position/rotation, then child every enemy to it right after it's created. You can iterate through them with a code like this (turret script):
var enemies: Transform; // drag the Enemies object to this field
...
for (var enemy: Transform in enemies){
if (EnemyInRange(enemy)){
// enemy inside range: shoot the bastard!
}
}
...
Thanks for helping, but I already tried this and it doesn't work. Just to be sure I hadn't missed something, I tried your code, but it still doesn't work.
@aldonaletto's code looks just fine (as it almost always is). I ran a quick test just to make sure, and it worked fine for me. It assumes you setup forwardDir correctly. It needs to be the forward of your selector in world coordinates. If you selector is in front of the camera, then you can use the camera forward (Camera.main.transform.forward).