Same premise as this question. When the ball bounces off of a wall, I want the ball to temporarily ignore all further collision events of the wall it just collided with, for three seconds for example. What's the best way to accomplish this?
Asked
Active
Viewed 4,479 times
2 Answers
3
There are several ways to do this, using a coroutine:
Disabling the collider
GetComponent<Collider>().enabled = false ;
StartCoroutine( EnableCollision( 3 ) ) ;
// ...
private IEnumerator EnableCollision( float delay )
{
yield return new WaitForSeconds( delay ) ;
GetComponent<Collider>().enabled = true ;
}
Turning the collider into a trigger
GetComponent<Collider>().isTrigger = true ;
StartCoroutine( EnableCollision( 3 ) ) ;
// ...
private IEnumerator EnableCollision( float delay )
{
yield return new WaitForSeconds( delay ) ;
GetComponent<Collider>().isTrigger = false;
}
Changing the layer
As indicated by Battle, you can use three layers and the collision matrix. Supposing your wall is in the Wall
layer, you can have another layer Ball
and PhantomBall
. Ball
/ Wall
will allow collision while PhantomBall
/ Wall
won't.
gameObject.layer = LayerMask.NameToLayer("PhantomBall") ;
StartCoroutine( EnableCollision( 3 ) ) ;
// ...
private IEnumerator EnableCollision( float delay )
{
yield return new WaitForSeconds( delay ) ;
gameObject.layer = LayerMask.NameToLayer("Ball") ;
}
Using Physics class
Supposing you have a reference to the wall collider
Physics.IgnoreCollision( GetComponent<Collider>(), wallCollider, true ) ;
StartCoroutine( EnableCollision( 3 ) ) ;
// ...
private IEnumerator EnableCollision( float delay )
{
yield return new WaitForSeconds( delay ) ;
Physics.IgnoreCollision( GetComponent<Collider>(), wallCollider, false ) ;
}

Hellium
- 2,949
- 1
- 11
- 27
0
You can use different layers which do not collide with each other. When bouncing one time, wait 0.5 seconds (maybe not necessary), then switch from layer A to B. After 3 seconds, set it back from B to A.
See also:
Unity Editor > Edit > Project Settings > Physics. You will find a table in which you can set it up as you need. Consider using your own custom layers for your game specific objects.

Battle
- 1,251
- 12
- 19