0
votes

I have enemies who face a certain direction, illustrated with a thick black line. I'd like to create a "view cone", which registers when the mouse enters it.

Here is my code:

  canSeeMouse(){

    stroke("#000000");
    strokeWeight(4);

    // Get a point 60px from the enemy, in the direction it is looking
    let lookingAt = p5.Vector.fromAngle(this.a).mult(60).add(this.p);
    // Draw a line for debugging.
    line(this.p.x, this.p.y, lookingAt.x, lookingAt.y);


    // Get the angle between this position and the players
    let toPlayer = Math.atan2(player.p.y - this.p.y, player.p.x - this.p.x);

    // if the angle from this to the player minus the angle this character is looking at is more than PI/4, stop
    if(Math.abs( toPlayer - this.a )  > (Math.PI/4)){
      return false;
    }
    if(this.p.dist(player.p) > 30){
      return false;
    }
    // Draw the sight line
    strokeWeight(1);
    stroke("#ffaaaa");
    line(this.p.x, this.p.y, player.p.x, player.p.y);
  }

And here is a demo: https://codepen.io/EightArmsHQ/pen/9ef2e8266f4cfb14b4ac177c135908b4?editors=0010

My issue is, I'm getting irregular results:

Illustration

Top right and bottom left are correct, the other two are showing the wrong view-cone.

I thought that it was due to one angle being between 0 and Math.PI*2, and the other being from an offset amount, so tried to use things like this:

if(Math.abs( toPlayer%(Math.PI*2) - this.a%(Math.PI*2) )  > (Math.PI/4)){

But that isn't it... I also tried switching the order of the subtraction:

if(Math.abs( this.a - toPlayer )  > (Math.PI/4)){

But that also didn't do the trick. I can't work out what part of my equation I'm doing wrong.

1

1 Answers

1
votes
if(Math.cos( toPlayer - this.a) >  Math.cos(Math.PI / 4))

solves all problems with order and with transition through zero