What is the cheapest way to prevent object A from going through object B


Both object A and object B have a kinematic rigid body attached; Interpolate: Interpolate, Collision Detection: Continous Speculate.

I’m using onTriggerEnter to detect the collision.

The problem is both object A and object B is moving very fast. And as you probably already know the faster an object moves the greater the travel distance between frames. So in one frame, there is a good amount of distance between object A and objectB and in the next frame object A pass-through object B.

My question is, is there a way to detect collision immediately on the impact between object A and object B? I know about raycasting and based on what I learn it’s expensive and it’s mostly used for extremely fast moving objects like a bullet.

Raycasts are only expensive when you use hundreds of them per frame. I’m using =~20 per frame on my project and it does not hurt performance heavily. But what you should use in this case if the collider’s bounds. If the closest distance from A to the bounds of B is smaller than the radius of A, than the ball is getting through B. Luckily, unity already has the functions for us. Code would look like:

Collider ColliderB = B.GetComponent<ColliderB>();
float distance = colliderB.bounds.sqrDistance;
if(distance <= A.radius){
    //the direction for going away
    Vector3 vector = A.transform.position - B.transform.position;
    //goes away by the distance to the collider + the radius of the ball
    A.transform.position += vector.normalized * (distance + A.radius)
}

In 2018.3 Unity introduced Speculative continuous collision detection. That should help with this if you’re not already using it.

Yes pls share the code…It will make easy for us to analyse issue and solve it

@xxTheo

In OnTriggerEnter() there is a way to detect which object is colliding with which object by checking the tag of colliding object.

Suppose your ObjectA has tag “ObjA”, you can check collision by:

private void OnTriggerEnter(Collider coll) { if(coll.CompareTag("ObjA")) { if(gameObject.name == "ObjectB") { Debug.Log("Collision happned with ObjectB "); } }

gameObject.name will give you the name of the object with which ObjectA is collided.

Hope this help :slight_smile: