Im working on getting one of my objects to ‘see’ another. At the moment I’m just doing a raycast but the problem with this is that it’s a single line. This means that unless another object is touching the line, it wont be seen. I need this object to instead have a field of sight branching out from it, similar to how we see. What would be the best way to do this?
Get the angle between the objects. Use Vector3.Angle(seeingThing.transform.position,thingToCheck.transform.posion);
Now see if that angle is within the visual fustrum you want. Say +/-45 degrees.
If so then you can do one or more raycasts between the seeing thing and the thing you are checking to make sure there is nothing blocking.
Usually this is done by measuring the angle between the target and the look direction: if it’s less or equal to the viewing angle, the object is potentially visible - you should then check if a raycast can hit the target without hitting something else in between:
var viewAngle: float = 30; // degrees from the center
function CanSeeYou(target: Transform): boolean {
var dir: Vector3 = target.position - transform.position; // find target direction
var angle: float = Vector3.Angle(transform.forward, dir); // find angle
var hit: RaycastHit;
if (angle <= viewAngle && // if inside viewing angle...
Physics.Linecast(transform.position, target.position, hit) &&
hit.transform == target){ // and nothing obscuring it...
// target is visible
} else {
// not visible
}
}
Call CanSeeYou(target) to check whether it’s visible:
function Update(){
if (CanSeeYou(enemy)){
// enemy at sight!
}
}
As a rule of thumb I always try to avoid recursive functions. Those are square root and all kind of trig functions.
So if Vector3.Angle is right, I would think it uses arccos within.
Now using dot you avoid the recursion.
Vector3 direction = player.position - _transform.position;
if (Vector3.Dot(direction.normalized, _transform.forward) > 0 )
{
// Object is front
}
0 means 180 degrees field of view, increasing the value will reduce the field, decreasing until -1 will give eagle eye.
All of those computations are simple arithmetic so pretty fast nowadays.