- Home /
Disable collision before collision actually happens
I'm basically trying to create Doodle Jump in Unity, but I need help with part of it. In the game, you can pass through blocks when you're below them, but jump when you're above it. My method for doing this is to disable collision when it detects the player is below the block, but the issue is that with OnCollisionEnter, it detects the collision when it happens. I need to be able to disable collision before the collision actually happens. Is there any way to do this?
private void OnCollisionEnter2D(Collision2D col)
{
Vector3 contactPoint = col.contacts[0].point;
Vector3 center = col.collider.bounds.center;
if (contactPoint.y > center.y)
{
rb.AddForce(new Vector2(0, 6), ForceMode2D.Impulse);
}
else
{
GetComponent<Collider2D>().enabled = false;
}
}
private void OnCollisionExit2D(Collision2D col)
{
GetComponent<Collider2D>().enabled = true;
}
As you noticed, the moment OnCollisionEnter*()
is called it is already too late, the collision happened, and the physics will run its course according to this.
However, you can detect if you are about to collide by using a separate trigger collider just above the player character and a simple script that has OnTriggerEnter*()
on it. You can also use this same script to disable either the block's or the player's collider, then enable it again in OnTriggerExit*()
. (Probably should only disable when the player jumps)
Answer by Dmytrenko · Jul 26, 2018 at 08:09 AM
For this purpose you can use PlatformEffector2D to create one-way platforms https://docs.unity3d.com/Manual/class-PlatformEffector2D.html
Your answer
Follow this Question
Related Questions
if statement not working when detecting collision between two prefabs 1 Answer
OnCollsionEnter2D not getting called 1 Answer
Resize Array Based on Value 2 Answers
Check for collision while animating 0 Answers
Destroying object on collision 3 Answers