So I’m attempting to make my first 2D platformer with Unity 2D, and I came across a somewhat specific problem regarding collision between an enemy and the player. Following a tutorial I found on YouTube, I set up the code for the enemy to patrol on platforms by using Vector2 lines that detect either the edge of a platform or a wall. My problem is that these lines also detect the player, so the player doesn’t take damage when the enemy collides with him. My guess is that the Box Collider 2D’s that I have set up are not touching due to the wall detection line hitting the player’s collider first, which turns the enemy around, so the Box Colliders never touch in the first place. I’m pretty sure that the code in the FixedUpdate method is the problem, but I just can’t seem to figure out a solution that works properly. I put the code down below for a better visual:
// Check to see if there's ground in front of us before moving forward
Vector2 lineCastPos = myTrans.position - myTrans.right * myWidth;
bool isGrounded = Physics2D.Linecast(lineCastPos, lineCastPos + Vector2.down, enemyMask);
bool isBlocked = Physics2D.Linecast(lineCastPos, lineCastPos - myTrans.right.toVector2() * .05f, enemyMask);
// If there is no ground, turn around. If there is a wall blocking the opossum, turn around
if (!isGrounded || isBlocked)
{
Vector3 currentRotation = myTrans.eulerAngles;
currentRotation.y += 180;
myTrans.eulerAngles = currentRotation;
}
// Always move forward
Vector2 myVel = myBody.velocity;
myVel.x = -myTrans.right.x * speed;
myBody.velocity = myVel;
Basically, my summed up question is this: Is there a way to make the wall detector ignore the player if it detects the player’s Box Collider?