I have 3 objects:
A capsule at vector (0,2,0).
A sphere at vector (5,2,5).
A cylinder at vector (10,2,10).
When I run the code:
foreach (RaycastHit hit in Physics.SphereCastAll(this.transform.position, 2, pos, 1000f)) {
Debug.Log (hit.collider.gameObject.name);
}
it logs Sphere, Cylinder and Capsule as expected.
However when I perform the spherecast in the opposite direction, there is a different result:
foreach (RaycastHit hit in Physics.SphereCastAll(pos, 2, this.transform.position, 1000f)) {
Debug.Log (hit.collider.gameObject.name);
}
It only logs Cylinder.
Why is this, surely both spherecasts should pass through the same objects?
Cheers.
The overload you are using here is
public static RaycastHit[] SphereCastAll(Vector3 origin, float radius, Vector3 direction, float maxDistance);
So the first parameter is a point in space, where the third parameter is a direction vector.
If “pos” is a direction vector and your raycast succeedes correctly in your first version, then of course it will return garbage on the second attempt. You are testing from a position that is a direction towards a direction that is a position…
But I guess that your “pos” is actually a position too and it just accidentely succeeded because it was “near 0,0,0”?
In any case: To do an overlap test “from one point to another point” you want this:
Vector3 origin = transform.position; // source point to test from
Vector3 pos = ...; // target Point to test towards
var hits = Physics.SphereCastAll(origin, 2, pos - origin, 1000f); // pos - origin = direction from origin towards pos.