Here is some of the script for the enemy:
if (isWall) {
StopAllCoroutines ();
if (dir == "R" && dir != "L") {
dir = "L";
transform.Translate (-1, 0, 0);
print ("SWITCHL");
isWall = false;
} else if (dir == "L" && dir != "R") {
dir = "R";
transform.Translate (1, 0, 0);
print ("SWITCHR");
isWall = false;
}
}
void OnTriggerEnter (Collider other) {
if (other.gameObject.tag == "SideCollide") {
isWall = true;
}
}
Half of the time the enemy does switch directions when hitting the trigger. Some times it just goes through and does not stop.
Well, the root may have something to do with collision detection. It may be valuable to set a log inside the OnTriggerEnter. If the speed is too high and/or the object too small, sometimes a collision will not register in a single frame, and something can “pass through” the collider. This is part of how physics are calculated. You can try making your walls colliders much larger temporarily as a test to see if that resolves it.
Also, don’t check if (dir == "R" && dir != "L")
, just check the positive if (dir == "R")
as the second part is inherent, but will make a second calculation anyway. If dir == 'R'
it inherently cannot also equal 'L'
. It’s a very tiny hit, but even this extra calculation could, in theory, take more time than you want during the collision.
Do SWITCHL and SWITCHR print when it passes through the collider, or does it appear not to get to the call at all?
Your code looks fine overall, and if it works sometimes then I suspect there’s no fault in what you’ve provided. My guess would be that the object is either moving too fast or you’ve got the wrong collision type on.