- Home /
Enemy AI's Raycast Ignoring Player
Hi!
I have a script below that makes my enemy AI dodge objects. But the script also makes it so the enemy dodges the player to. This is a problem when my enemy is shooting at my player and keeps dodging it so the bullets never hit him. If anyone could help me fix the script or edit it that would be great. I tried using layers but i'm not so good with those. Thanks in advance!!!
function Update()
{
// the directional vector to the target
dir = Vector3.forward * Time.deltaTime * 2;
var hit : RaycastHit;
// check for forward raycast
if (Physics.Raycast(transform.position, transform.forward, hit, 15)) // 20 is raycast distance
{
if (hit.transform != transform)
{
if (Physics.Raycast (transform.position, transform.TransformDirection
(Vector3.forward), hit, Mathf.Infinity)) {
Debug.DrawRay (transform.position, transform.TransformDirection (Vector3.forward) *
hit.distance, Color.yellow);
print ("Did Hit");
}
else {
Debug.DrawRay (transform.position, transform.TransformDirection (Vector3.forward) *1000,
Color.white);
print ("Did not Hit");
}
Debug.DrawLine (transform.position, hit.point, Color.white);
dir += hit.normal * 2; // 20 is force to repel by
}
}
// more raycasts
var leftRay = transform.position;
var rightRay = transform.position;
leftRay.x -= 2;
rightRay.x += 2;
// check for leftRay raycast
if (Physics.Raycast(leftRay, transform.forward, hit, 15)) // 20 is raycast distance
{
if (hit.transform != transform)
{
Debug.DrawLine (leftRay, hit.point, Color.red);
dir += hit.normal * 2; // 20 is force to repel by
}
}
// check for rightRay raycast
if (Physics.Raycast(rightRay, transform.forward, hit, 15)) // 20 is raycast distance
{
if (hit.transform != transform)
{
Debug.DrawLine (rightRay, hit.point, Color.green);
dir += hit.normal * 2; // 20 is force to repel by
}
}
// Movement
var rot = Quaternion.LookRotation (dir);
transform.rotation = Quaternion.Slerp (transform.rotation, rot, Time.deltaTime);
}
Answer by Ravenmore · May 13, 2012 at 07:08 PM
You're only checking if the object hits itself:
if (hit.transform != transform)
except for that line your code disregards completely the type of object the raycast hits. Hence the enemy AI will dodge everything except itself =)
You need to add a check for the object's tag, and if it's (for example) "player" then skip the dodging behaviour.
Just set the player's tag to "Player" (it's one of the default ones) And then do:
if (hit.transform != transform && hit.transform.tag != "Player"){
(dodge code here)
}
So you have the AI thinking "if it's not me and not the player, I will start dodging" :)
O$$anonymous$$ it works!!! Thanks for the responce but one quick question. Does != mean the oppisite of ==? THAN$$anonymous$$S! Also, The enemys shots are always to the left of the player when the dodge script is attached...any ideas? THAN$$anonymous$$S!!!