I use OverlapSphereNonAlloc to detect collision of my player with wall/s in the scene.
Once the collision detected I want to calculate the normal, similarly to RaycastHit.normal.
OveralSphereNonAlloc, allows to get ClosestPoint or ClosestPointOnBounds:
var collisionPoint = colliders[0].ClosestPointOnBounds(transform.position);
I also have the rotation of the wall, and the position of the player.
How can I calculate a normal using this data? What other data do I need to calculate the normal of the collided wall with the player?
To calculate the normal vector of a surface using the OverlapSphereNonAlloc function in Unity, you can use the following steps:
First, call the OverlapSphereNonAlloc function and pass in the center point of the sphere, the radius of the sphere, and an array to store the colliders that the sphere overlaps with. This will return the number of colliders that the sphere overlapped with.
Next, iterate through the array of colliders and for each collider, get the normal of the surface that the sphere is colliding with. You can do this by calling the Collider.ClosestPoint function on the collider and passing in the center point of the sphere as the point to find the closest point to. This will return the closest point on the surface of the collider to the center of the sphere, which you can then use to calculate the normal vector of the surface using the cross product of the vectors from the center of the sphere to the closest point on the collider and from the closest point on the collider to the center of the sphere
Code:
// The center point of the sphere
Vector3 sphereCenter = new Vector3(0, 0, 0);
// The radius of the sphere
float sphereRadius = 1.0f;
// The array to store the colliders that the sphere overlaps with
Collider overlappingColliders = new Collider[10];
// Call OverlapSphereNonAlloc to get the number of colliders that the sphere overlaps with
int numOverlappingColliders = Physics.OverlapSphereNonAlloc(sphereCenter, sphereRadius, overlappingColliders);
// Iterate through the array of colliders and calculate the normal vector of the surface that the sphere is colliding with
for (int i = 0; i < numOverlappingColliders; i++)
{
// Get the collider that the sphere is colliding with
Collider collider = overlappingColliders*;* // Get the closest point on the collider to the center of the sphere Vector3 closestPoint = collider.ClosestPoint(sphereCenter); // Calculate the normal vector of the surface using the cross product // of the vectors from the center of the sphere to the closest point on the collider // and from the closest point on the collider to the center of the sphere Vector3 surfaceNormal = Vector3.Cross(closestPoint - sphereCenter, sphereCenter - closestPoint).normalized; // Use the surface normal vector to do something, such as apply a force in the opposite direction }