- Home /
How do I make object only collide with certain objects based on position of collision within the collider?
I am making a 2D platformer. The character is a 100X100 sprite that has about 20 pixels blank at the bottom. The purpose of this is to give the illusion of floating. The player's collider goes to the bottom of its sprite and the platforms have edge colliders on the very top of them. The issue is that if a player hits an enemy or obstacle from above, the player hits it when the collider (below where the player visually is) hits the obstacle. What I want to do is simply say that the collision with the obstacle occurs only at a lower point, but I don't even know if this is the right approach. I'm open to ideas of any kind.
Answer by highpockets · May 27, 2019 at 09:24 PM
In a situation like this, I would opt for 2 colliders and get the lower one to ignore collisions with everything except for the ground and the other one can collide with enemies/obstacles/etc. You can use the layer collision matrix to define what collider layers to ignore. Check out this post:
https://answers.unity.com/questions/686915/how-do-i-get-some-objects-to-ignore-collision-with.html
Thanks @highpockets , how do I make 2 separate colliders that use the layer collision ignore if it goes by tag and they both have the same tag (because they're attached to the same object). I had originally tried to do this using 2 children and attaching the colliders to the children that each had a different tag, but the collider that actually prevents the user from falling through the platforms doesn't hold the player up unless it's attached to the player. I then tried keeping that one on the player, but then the problem was that the collider labelled player was not colliding with the obstacles while the other one was. I guess this is okay, but it seems like a very non-correct and non-elegant way to hack around it. Can you label the 2 colliders on the player seperately? That would be a lot cleaner.
Well the layer matrix is the way to do it in the editor, and having the bottom one a child of the top one and then putting the layers on them and defining what you need in the matrix is one way to do it.
You can also use the Physics.IgnoreCollision() function:
https://docs.unity3d.com/ScriptReference/Physics.IgnoreCollision.html