# Thread: Line of Sight between 2 objects

1. Member
Join Date
Oct 2011
Posts
1
Rep Power
0

## Line of Sight between 2 objects

ok so basically I have a 2D game and I am programming an AI ... using the good old a2+b2=c2 I am able to get the distance between my player and my monster .. (this calculates his range.. whether he will stop his random patrol and chase you or not)

However, now i want to add the ability to be within his range, and him to not see you, or you can hide behind a wall, and he will stop shooting..

so far my code is as follows.. ( to calculate distance based on center of the player and creature)
HOW DO I TEST IF THERE IS ANYTHING BETWEEN THE PLAYER AND CREATURE... SHOULD I USE A LINE OR A BOX? I THINK IM IN OVER MY HEAD ON THIS ONE =D
I HAVE A SEPERATE ARRAYLIST OF "currentTerrainObj" so we dont have to worry about other creatures or players getting in the way of the calculation. I dont think we can use a box, because if it is 300 pixels away a tree might be in the far corner and the AI would chase or shoot, yet he would have complete line of sight.. please help =D

public void creatureShoot(){
int xDistance, yDistance;
int playerX, playerY, creatureX, creatureY,totalDistance;
for (int j = 0; j < currentCreatureObj.size(); j++) {
playerX = (int) (playerEnt.x + (playerEnt.sprite.getWidth())/2);
playerY = (int) (playerEnt.y + (playerEnt.sprite.getHeight())/2);
creatureX = (int)(currentCreatureObj.get(j).x + (currentCreatureObj.get(j).sprite.getWidth())/2);
creatureY = (int)(currentCreatureObj.get(j).y + (currentCreatureObj.get(j).sprite.getHeight())/2);

xDistance = Math.abs(playerX-creatureX);
yDistance = Math.abs(playerY-creatureY);
totalDistance = (int) Math.sqrt(Math.pow(xDistance,2)+Math.pow(yDistance ,2));

if ( totalDistance <= SHOOTING_RANGE ) {
System.out.println(totalDistance +" creature in range of player, should shoot now");
}
}
}
Last edited by mdpx; 10-15-2011 at 02:05 AM.

#### Posting Permissions

• You may not post new threads
• You may not post replies
• You may not post attachments
• You may not edit your posts
•