Reputation: 45
I have already read other questions on this and none of them fix my issue. I am making a game where the AI moves back if it gets to close to the player [a ray cast toggles a bool if the ray hits at a certain distance], however because this is in the update function, the ray updates every frame and then toggles the bool when I don't want it to as I have already initiated the code to make the AI move back, please can someone tell me how to use a layer mask to temporarily stop the ray cast when the 'avoid' bool is true and so the ray cast is ignored when the AI is moving backwards, code;
void Update ()
{
//raycasting
RaycastHit hit;
Ray ray = new Ray(transform.position, Vector3.forward);
//check if raycast hit player
if (Physics.Raycast(ray, out hit, 2))
{
if (hit.collider.tag == "PlayerFront")
{
avoid = true;
movementSpeed = 0;
}
}
else
{
movementSpeed = 2f;
avoid = false;
}
if (avoid == true)
{
startPos = enemy.transform.position;
endPos = enemy.transform.position + Vector3.back * distance;
currentLerpTime += Time.deltaTime;
if (currentLerpTime >= lerpTime)
{
currentLerpTime = lerpTime;
}
float perc = currentLerpTime/lerpTime;
enemy.transform.position = Vector3.Lerp(startPos, endPos, perc);
avoidCount+=1;
avoid = false;
}
else if (avoid == false)
{
transform.LookAt(target);
transform.Translate(Vector3.forward * Time.deltaTime * movementSpeed);
currentLerpTime = 0;
}
}
Upvotes: 0
Views: 988
Reputation: 34218
My suggestion would be to put the if (Physics.Raycast...
block inside the else
block at the bottom of your code. (Note that else if (avoid == false)
is redundant since there's no other value avoid
could be if it's not true
.
This would mean that you only raycast when you are not already avoiding, which will accomplish what you ask and also be more performant.
However, it's also worth noting that your code currently sets avoid = false
in the if
block - so you will only currently avoid for a single frame at a time. You might perhaps consider finding a way to leave avoid
as true
for a longer period of time.
Upvotes: 1