Check if an object is facing another based on angles
- by Isaiah
I already have something that calculates the bearing angle to get one object to face another. You give it the positions and it returns the angle to get one to face the other.
Now I need to figure out how tell if on object is facing toward another object within a specified field and I can't find any information about how to do this.
The objects are obj1 and obj2. Their angles are at obj1.angle and obj2.angle. Their vectors are at obj1.pos and obj2.pos. It's in the format [x,y]. The angle to have one face directly at another is found with direction(obj1.pos,obj2.pos).
I want to set the function up like this: isfacing(obj1,obj2,area){...}
and return true/false depending if it's in the specified field area to the angle to directly see it.
I've got a base like this:
var isfacing = function (obj1,obj2,area){
var toface = direction(obj1.pos,obj2.pos);
if(toface+area >= obj1.angle && ob1.angle >= toface-area){
return true;
}
return false;
}
But my problem is that the angles are in 360 degrees, never above 360 and never below 0. How can I account for that in this? If the first object's angle is say at 0 and say I subtract a field area of 20 or so. It'll check if it's less than -20! If I fix the -20 it becomes 340 but x < 340 isn't what I want, I'd have to x 340 in that case.
Is there someone out there with more sleep than I that can help a new dev pulling an all-nighter just to get enemies to know if they're attacking in the right direction? I hope I'm making this harder than it seems.
I'd just make them always face the main char if the producer didn't want attacks from behind to work while blocking. In which case I'll need the function above anyways.
I've tried to give as much info as I can think would help. Also this is in 2d.