This forum is read only and just serves as an archive. If you have any questions, please post them on

9 years ago by Filip

I've been struggling with a problem all week that seems like it should have a simple solution but I can't get it right.

I've got an enemy/prey entity being hunted by the player/hunter entity in a top down game.

I have a line of sight check working fine to check if one can see the other based on distance and obstacles in the path (using the great line of sight plugin).

However, I would like this check to happen only if the enemy is facing the player using currentAnim.angle and angleTo(this.player).

The problem I'm having is the way the angles are calculated. (I've converted them to degrees to make it make slightly more sense in my head).

If the enemy is facing 90 degrees (or 0/up) I can do a conditional statement that checks whether this angle is <= (the angle to the player + 90) and >= (the angle to the player -90). This just about works at that angle. The problem is that after 180 degrees (or 1.57 radians) the angleTo suddenly switches from +180 to -180 which makes the conditional statement not work when the enemy entity is facing another angle. I see why it's doing this but it makes calculations really difficult.

This is probably more of a maths question than an Impact one but I have tried and asked colleagues/mathematical friends and none of the attempts/suggestions I've got work.

Has anyone done something similar or have an idea of how to go about such a conditional check?

UPDATE: As usual, you post these things just before you get a solution. A friend just helped out with a check that seems to work. Along the lines of:

var anglefromprey = (angleTo(this.player) *180)/Math.PI (for some reason also had to add 90 degrees to this to make it line up correctly).
var preyfacingangle = (this.currentAnim.angle * 180)/Math.PI

if (
anglefromprey > preyfacingangle - (180 * 0.5) && anglefromprey < preyfacingangle + (180 * 0.5) || anglefromprey + 360 > preyfacingangle - (180 * 0.5) && anglefromprey + 360 < preyfacingangle + (180 * 0.5)

9 years ago by dungeonmaster

I didn't check if currentAnim.angle also is in -+180 range like angleTo. If so, use this (in enemy.update):
var sightRange = Math.PI / 8 // 45 (*2 = 90degs.) sight range
if (Math.abs(this.angleTo(thePlayer)-currentAnim.angle()) <= sightRange)

If not; like if the currentAnim.angle is within 0..360 degs, use this:
var properAngle = (this.angleTo(thePlayer) + 2*Math.PI)%Math.PI

This should always give an angle within 0..2pi (0..360deg) range. Then use the above code with properAngle.

9 years ago by Filip

Thank you! I may use that to tidy things up and in case I need to do this sort of thing again. It took me ages to figure out what was going wrong until I printed out the current angles to the screen and watched them change. 360 degrees throughout the system seems to make most sense.
Page 1 of 1
« first « previous next › last »