here is an image ( I cant post )show what I am gonna to do in my XNA game , I want to check if the player is inside zone range and if yes then attack the player , I tried to do this using checking ray but it's odd and give null results as player must be in front of enemy so he can be detected ! ![enter image description here][1]
if (enemyRay.Intersects(cci.CharacterController.Body.CollisionInformation.BoundingBox) <= 200)
{
RunController(dwarfAnimatior, dwarfwalk);
dwarfChrachterController.Body.ApplyImpulse(dwarfChrachterController.Body.OrientationMatrix.Forward,
Vector3.Normalize(enemyRay.Direction) * 50.0f);
if (enemyRay.Intersects(cci.CharacterController.Body.CollisionInformation.BoundingBox) <= 50)
{
sound.playAh();
}
}
You need to do two things:
Check the distance between the player's position and the enemy position.
Check that the angle made by the line between the player and enemy & the line pointing in the direction of the player's view is less than 180degrees.
The first is easy:
bool isCloseEnoughToAttack = Vector.Magnitude( Math.abs(player.position - enemy.position) ) < distanceToStartAttacking
The second is a little more complicated. As long as you don't need to be really particular about what 'in-front of player' means, you can fairly easily check the angle is not behind by checking the Dot Product is greater than 0:
bool isInFrontOfPlayer = Vector.DotProduct(Vector.Normalize(player.position - enemy.position), player.lookAtDirection) > 0
Note - This code is psudeocode, I don't know the exact naming of your variables/libraries; but it should be fairly similar.