Hello,
I have wrote a little enemy movement script (only idle movement so far), and I have trouble keeping my enemy behind the walls. I have a 2D game, so the camera is orthographic from above.
The enemy has a script attached that does the following:
void Update ()
{
if (target == null) {
if (frameSkip == 5 && movementCalculating == false) {
IdleMovement ();
frameSkip = 0;
}
} else {
ChasePlayer ();
}
frameSkip++;
}
target is set when the player enters the enemie’s circlecollider. Frameskip so movement will be smoother.
Then the IdleMovement() function:
void IdleMovement ()
{
movementCalculating = true;
var randomDirection = movementVectors [Random.Range (0, 4)];
var wallAhead = AnyWalls (randomDirection);
if (!wallAhead) {
PlayMoveAnimation (randomDirection);
transform.Translate (randomDirection * Time.deltaTime * movementSpeed);
}
movementCalculating = false;
}
The movementVectors are defined as follow:
movementVectors = new Vector2[4] {
Vector2.left,
Vector2.up,
Vector2.right,
Vector2.down
};
The AnyWalls() function is my 2D Linecast:
bool AnyWalls (Vector2 dir)
{
Vector2 start = transform.position;
Vector2 end = start + dir;
myCollider.enabled = false;
var hit = Physics2D.Linecast (start, end, rayCastLayerMask);
myCollider.enabled = true;
if (hit.transform != null) {
return true;
} else {
return false;
}
}
The rayCastLayerMask is set to the blocking layer, the same layer the walls are on.
The problem is that the enemy is walking through walls as if there were none.
I have no idea why this isn’t working.
Any help would be greatly appreciated!
Thanks,
Sym