2
\$\begingroup\$

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?

\$\endgroup\$
3
\$\begingroup\$

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 ) ;
}
\$\endgroup\$
0
\$\begingroup\$

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.

And some documentation.

And how to set layer via script.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.