- Home /
How Do I Ignore a Collision Between an Enemy and the Player?
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?
Answer by Uios-Theou · Feb 17, 2019 at 05:18 PM
Set up a layermask for the ground objects and make sure the only thing tagged with that layermask is the ground. Then ensure the raycast is only checking on that layermask so it ignores anything outside that mask.
That solution works perfectly, thank you so much for the help. Don't know why I didn't think of that sooner!
Happy to help. Feel free to mark the question as answered for others who might be searching for the same solution.
Your answer
![](https://koobas.hobune.stream/wayback/20220612191901im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
How to destroy all enemies within a certain collider? 1 Answer
Enemy ai Ignore walls! help! 1 Answer
Wall checking not working correctly 2 Answers
Enemy not taking damage on collisions. 2 Answers