- Home /
Raycast to check for potential pitfalls
Currently I have my enemies moving around using Raycast obstacle avoidance. "if (checkObstacles)"
The code below steers the enemy away from obstacles. Right now, I'm trying to have my enemies check ahead and down to see if there isn't any thing there, and if so, steer the enemy away from an potential pit until he detects a surface.
The direction Vector is the enemy's movement, and this code basically "rotates" the enemy by manipulating the direction vector.
Right now, I am having trouble with both making the raycast shoot forward and down in the if statement that starts off "if (checkPitfalls)". The enemy doesn't acknowledge the lack of a raycast collision and just keeps running off the level.
//First Offset where the ray should end up
Vector3 pitRayOffset = new Vector3(0, 0, 1);
//Then Shoot it down
Vector3 pitCheckRay = trans.TransformDirection(0, -2, 0);
if (checkPitfalls)
{
Debug.DrawRay(trans.localPosition + pitRayOffset, (pitCheckRay) * 2, Color.cyan);
RaycastHit groundCheck;
if (!Physics.Raycast(trans.localPosition + pitRayOffset, pitCheckRay, out groundCheck, 2))
{
print("NO GROUND");
Debug.DrawRay(trans.localPosition + pitRayOffset, (pitCheckRay) * .5f, Color.red);
direction = -direction;//+= (direction.magnitude * groundCheck.normal) * (percision * Time.smoothDeltaTime);
}/*raycast*/
}/*for loop*/
direction.Normalize();
direction.y = _holdTheJump;
steeringRays.Clear();
Quaternion rot = Quaternion.LookRotation(new Vector3(direction.x, 0, direction.z));
trans.rotation = Quaternion.Slerp(trans.rotation, rot, 3 * Time.smoothDeltaTime);
I edited the script down to where the problem lies. The offset for the ray isn't rotating correctly when the enemy moves, so it isn't offsetting correctly.
In a nutshell, the ray isn't facing the forward direction: [Topdown view]
Answer by Eric5h5 · Sep 05, 2010 at 06:31 AM
You can tag the boundaries with a unique tag, and use the results from FindGameObjectsWithTag to loop through each boundary with Physics.IgnoreCollision and the player, so the player will go through the boundaries but nothing else will.
Or use layer-based ignore collisions in Unity 3.
To avoid confusion, this question has been redone since Eric Last answered it :)