I’ve tried searching for the answer to this over the last couple days but have had no luck finding anything addressing my scenario, hence this post.
I’d like to know if it’s possible to create a raycast which has a fixed distance and get the position at the end point of the raycast (without the raycast needing to register a collision with another object).
I have tried experimenting with Ray.GetPoint but even when trying the Unity example my console print out reads ‘(0.0, 0.0, 0.0)’.
I’m sure I’m missing something basic but after spending so long without making any progress I’m hoping someone else can help point me in the right direction.
Oh man, Unity put up a TERRIBLE example for that API. The default Ray() constructor produces a ray with direction of Vector3.zero, so no matter how far you go down that array, you are at (0,0,0).
Try this instead:
Ray r = new Ray( origin: Vector3.zero, direction: Vector3.forward + Vector3.up);
print(r.GetPoint(10)); // a point 10 units along the ray
Edit: I posted a suggestion to the API to improve it. You can make a post too saying it was confusing to you.
EDIT: updated the above code to used named arguments, since the two arguments have the same type.
Many thanks Kurt, that really helped clear things up.
I used it to generate a projected position ahead of a player based on their current speed. Here’s the code in case anyone is interested in an example:
// Update is called once per frame
void Update()
{
// Calculate the length the player projection needs to be using the velocity magnitude.
distanceToProject = baseProjectionDistance * player.GetComponent<AircraftInstruments>().airspeed / maxAirspeed;
// Convert vehicle 'local space' forward into 'world space' forward.
Vector3 forward = transform.TransformDirection(Vector3.forward);
// Draw ray forward from player.
Ray r = new Ray(player.transform.position, forward);
// Get position at the end of the raycast.
projectionPos = r.GetPoint(distanceToProject);
// Debugging.
if (debugging)
{
print(r.GetPoint(distanceToProject));
Debug.DrawRay(transform.parent.position, forward * distanceToProject, Color.blue);
}
}