line of sight, 2D topdown tile game
in
Programming Questions
•
1 year ago
I'm making an overhead shooter, but I'm having trouble with the 'cone of sight' of the enemy. What I want is for the enemy to only detect the player if he is in front of him (ie in his cone of sight). Here is a screenshot
and here is the code I'm having trouble with:
- boolean PointInViewAngle(float objX, float objY, float coneX, float coneY, float coneDir, float coneAngle) {
boolean seeMe = false; //this WILL BE returned as TRUE at the END of the funciton if the enemy can see the player
float minAngle = coneDir - coneAngle / 2; //the minimum angle of the code (ie 1 of the red lines)
float maxAngle = coneDir + coneAngle / 2; //the max angle of the code (ie 1 the other red line)
float thisAngle = atan2(objY - coneY, objX - coneX); // objX,objY = player, coneY = of the enemy)
//Test if the angle is inside the 'cone' (between the min angle and max angle)
if (minAngle > maxAngle) {
if ((thisAngle <= maxAngle) ||(thisAngle >= minAngle)) {
seeMe = true;
}
}
return seeMe;
}
void enemiesDraw() {
//Draw a visual representation of the cone of sight (+16 to center it on the enemy image)
stroke(255,0,0);
line(x*+16,y+16,x + (cos(angle+radians(45)/2)*400)*tileSize,y + (sin(angle+radians(45) / 2)*400*tileSize));
line(x*+16,y+16,x + (cos(angle-radians(45)/2)*400)*tileSize,y + (sin(angle-radians(45) / 2)*400*tileSize));
//if the enemy can see the player, print a message.
if (PointInViewAngle(player1.x+offsetX,player1.y+offsetY,x*tileSize+offsetX,y*tileSize+offsetY,angle,radians(45)) == true) {
print("I can see you");
}
Any help is widely appreciated
1