
コライダーのcontactOffsetを使ってみました。
Boxコライダーの付いたCubeにSphereを衝突させます。OnCollisionEnterでCubeを赤くして、OnCollisionExitで白に戻します。
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ColliderTest2 : MonoBehaviour
{
[SerializeField] float contactOffset;
Collider coll;
MeshRenderer rend;
// Start is called before the first frame update
void Start()
{
coll = GetComponent<Collider>(); // コライダーを取得
coll.contactOffset = contactOffset; // contactOffsetを設定
rend = GetComponent<MeshRenderer>(); // メッシュレンダラーを取得
}
private void OnCollisionEnter(Collision collision)
{
rend.material.SetColor("_BaseColor", Color.red); // 赤くする
}
private void OnCollisionExit(Collision collision)
{
rend.material.SetColor("_BaseColor", Color.white); // 白くする
}
}
コライダーのcontactOffsetはデフォルトでは0.01ですが、3に設定してみます。

すると、Sphereが衝突する前にCubeが赤くなり、バウンドした後もしばらく赤いままです。

Boxコライダーが大きくなったわけではないですが、衝突を検出する範囲が広がったことがわかります。
SphereのコライダーにもcontactOffsetを設定してみました。
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Cannon : MonoBehaviour
{
[SerializeField] GameObject ball;
[SerializeField] float contactOffset;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
if(Input.GetKeyDown(KeyCode.E))
{
GameObject b = Instantiate(ball, transform.position, transform.rotation); // 球を生成
Collider coll = b.GetComponent<Collider>(); // コライダーを取得
coll.contactOffset = contactOffset; // contactOffsetを設定
coll.attachedRigidbody.AddForce(transform.right * 20f,ForceMode.Impulse); // 力を加える
}
}
}

すると、さらに手前でCubeが赤くなるようになりました。

リファレンスにも「合計よりも距離が小さい場合」とあります。https://docs.unity3d.com/ja/current/ScriptReference/Collider-contactOffset.html