Advertisement

Check if enemy can see player

Started by July 21, 2013 01:40 PM
2 comments, last by robee00 11 years, 7 months ago

Hello!

I encountered some problem with ray collision.

I want to detect if enemy can see the player. I cast a ray from the enemy's position in the direction of the player. If the first thing that the ray hits is the player, then the enemy can see the player. I store all of the AABB's in an ArrayList(no optimizations yet, just trying to solve it, no oct-tree, nothing :P). The problem is that I check if the ray hit any object with a foreach. So, even if the enemy can see the player, the method return false, because it hit a wall first in the terms of the list. Should I sort the list somehow? Smaller X positions first, then sort by Z?

Thanks in advance!

Cheers, R

Create a Ray intersection test that returns the distance from ray position to collision. If the distance is greater than the distance from enemy to player, disregard that test and move on to the next item in the arraylist. Only consider the enemy to be able to see the player if no object returns a value less than the player/enemy distance.

Some frameworks, like XNA, come with this kind of test. Even if you don't use XNA you can bring its test code up on reflector and see how it works to make your own test in whatever language you're using.

Advertisement

Hello!

I encountered some problem with ray collision.

I want to detect if enemy can see the player. I cast a ray from the enemy's position in the direction of the player. If the first thing that the ray hits is the player, then the enemy can see the player. I store all of the AABB's in an ArrayList(no optimizations yet, just trying to solve it, no oct-tree, nothing tongue.png). The problem is that I check if the ray hit any object with a foreach. So, even if the enemy can see the player, the method return false, because it hit a wall first in the terms of the list. Should I sort the list somehow? Smaller X positions first, then sort by Z?

Thanks in advance!

Cheers, R

So, just to make sure I understand, the result you get back from the raycast is an unordered list of AABBs? One of whom may be the player? If that is that case, it is probably easiest and most efficient to do two passes through the list; first to find the player (early out if the player is not found), and the second to see if the player is the first object hit. This is 2 linear operations so it scales as O(n) for n objects in the list. If you sort the list it, should scale as O(n*log(n)). So the simple, straight-forward approach is best.

-Josh

--www.physicaluncertainty.com
--linkedin
--irc.freenode.net#gdnet

I did it, I used the distance method that shazem given. I get the object with the smallest distance that collided with the ray. If it's the player's AABB, then gotcha, the enemy can see the player.

This topic is closed to new replies.

Advertisement