Reputation: 165
I'm trying to create a curved Ray and need to list the object that curved Ray hits. I am able to draw a curved Ray with Debug.DrawRay(). However, When I provide Raycast() the same parameters with DrawRay(), It's creating very different Ray (I guess because I can't see the Ray). The Raycast()'s Ray hits the object I highlighted in the image. But DrawRay()'s Ray is too far to hit the highlighted object. How can I make them create identical Rays?
//Here is the code:
public void CurveCast(Vector3 origin, Vector3 direction, Vector3 gravityDirection, int smoothness, float maxDistance, float direction_multiply, float radius)
{
Vector3 currPos = origin, hypoPos = origin, hypoVel = (direction.normalized / smoothness) * direction_multiply;
List<Vector3> v = new List<Vector3>();
float curveCastLength = 0;
Ray ray;
RaycastHit hit;
hit_list = new List<RaycastHit>();
while (curveCastLength < maxDistance)
{
ray = new Ray(currPos, hypoVel);
Debug.DrawRay(currPos, hypoVel, Color.white);
if (Physics.Raycast(currPos, hypoVel, out hit)) // if (Physics.SphereCast(ray, radius, out hit,maxDistance))
{
hit_list.Add(hit);
}
v.Add(hypoPos);
currPos = hypoPos;
hypoPos = currPos + hypoVel + (gravityDirection * Time.fixedDeltaTime / (smoothness * smoothness));
hypoVel = hypoPos - currPos;
curveCastLength += hypoVel.magnitude;
}
}
Upvotes: 3
Views: 6683
Reputation: 4112
It is because Debug.DrawRay
and Physics.Raycast
are not exactly the same.
In Debug.DrawRay
, the length of the ray is defined by the vector magnitude. You can see it in the doc:
Draws a line from start to start + dir in world coordinates.
For Physics.Raycast
, the length of the ray is independant from the direction and can be set as a parameter. Its default value is infinite, so if you don't define it, the raycast will go to infinity, even if the direction vector is short. See the doc:
Casts a ray, from point origin, in direction direction, of length maxDistance, against all colliders in the scene.
So the solution for you is to give the proper distance to the Raycast function:
Debug.DrawRay(currPos, hypoVel, Color.white);
if (Physics.Raycast(currPos, hypoVel, out hit, hypoVel.magnitude())) // if (Physics.SphereCast(ray, radius, out hit,maxDistance))
{
hit_list.Add(hit);
}
Upvotes: 5