- Home /
Eficient one-way collider
Hello, I am trying to make a player character collide on some platforms only from the top and ignore any other collision for a 2D-style game. I came up with this solution as a script attached to the platform(s)
public class PlatformCollision : MonoBehaviour
{
public Transform playerPosition;
private Transform myTransform;
void Start()
{
myTransform=this.transform;
}
void Update()
{
if(playerPosition)
{
Vector3 distance = playerPosition.position - myTransform.position;
if(distance.y>=0)
{
collider.enabled=true;
}
else
{
collider.enabled=false;
}
}
}
}
What I don't like about this is the fact that I'm checking for the player's position relative to the platform on every frame. My question is: Is there a better way to do this?
PD: I have tried the solution suggested here http://answers.unity3d.com/questions/236313/one-way-collider.html but the player character was colliding with the plane from the sides
Answer by Screenhog · Dec 10, 2012 at 09:56 PM
The best way I've seen this done is with Physics.IgnoreCollision. IgnoreCollision can be set to true or false, and can control if an object colliders with or ignores another collider.
Let's say that you have a platform, made from a simple Unity box. You parent a trigger object to the box, looking like this:
___________
| platform|
---------------
| |_________| |
| trigger |
---------------
In scripting, you say that if your character enters the trigger (OnTriggerEnter), use Physics.IgnoreCollision to make the character ignore the platform's existence. When the character leaves the trigger (OnTriggerExit), use Physics.IgnoreCollision again (set to false) to make the character able to collide with the platform again.
Does this make sense?
I know this is super old but I really need help with this, what would the script look like? I have a deadline by Friday.
Answer by ROBOTunderscore · Apr 06, 2015 at 02:59 PM
Unity 5 has support for 2D one-way platforms. Just add a component to your platform called "Platform Effector 2D."
Answer by sattri99 · Dec 30, 2013 at 09:22 AM
I've made a tutorial recently on efficient one way collider with source code available on my blog. It's based on Faricho's idea and it's the most wfficient way of creating one way colliders. Youca check it out on my blog. Link -- Click here to see it
Answer by LostInCode404 · Jul 09, 2014 at 01:44 PM
What u can do is make a collider just below the platform to check if the player is colliding the platform from below so that We can disable the platform at that time, try out this tutorial http://newtonians3d.blogspot.in/2014/07/one-way-platform-unity-tutorial.html