I was surprised while looking at the unity 2d documentation that there isn’t a simple arc raycast. These are useful for things like jumping, testing the path of projectiles before shooting and other AI goodness.
Here’s the raw code to a simple one. It uses an initial velocity and acceleration, along with some limits to allow you to do a “natural” raycast that returns any colliders along the path.
The result will let you do things like this:
<pre>
public static void GetArcHits( out List<RaycastHit2D> Hits, out List<Vector3> Points, int iLayerMask, Vector3 vStart, Vector3 vVelocity, Vector3 vAcceleration, float fTimeStep = 0.05f, float fMaxtime = 10f, bool bDebugDraw = false )
{
Hits = new List<RaycastHit2D>();
Points = new List<Vector3>();
Vector3 prev = vStart;
Points.Add( vStart );
for ( int i = 1; ; i++ )
{
float t = fTimeStep*i;
if ( t > fMaxtime ) break;
Vector3 pos = PlotTrajectoryAtTime (vStart, vVelocity, vAcceleration, t);
var result = Physics2D.Linecast (prev,pos, iLayerMask);
if ( result.collider != null )
{
Hits.Add( result );
Points.Add( pos );
break;
}
else
{
Points.Add( pos );
}
Debug.DrawLine( prev, pos, Color.Lerp( Color.yellow, Color.red, 0.35f ), 0.5f );
prev = pos;
}
}
public static Vector3 PlotTrajectoryAtTime (Vector3 start, Vector3 startVelocity, Vector3 acceleration, float fTimeSinceStart)
{
return start + startVelocity*fTimeSinceStart + acceleration*fTimeSinceStart*fTimeSinceStart*0.5f;
}
</pre>