Breaking Open the Black Box

The Secrets and Stories of Game Design

Pages

  • Game Design Lessons
  • Learning From My Past
  • Post-Mortems
  • Who am I?
Follow @Xelnath [mc4wp_form]

Powered by Genesis

Doing a simple 2d Arc Raycast in Unity

2016.03.04 by Xelnath Leave a Comment

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:

CarverBug_BurrowLines

<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>

Filed Under: Uncategorized

March 2016
M T W T F S S
 123456
78910111213
14151617181920
21222324252627
28293031  
« Dec   May »

Blog Stats

  • 226,110 hits

Leave a Reply

Your email address will not be published. Required fields are marked *

Archives

  • August 2022
  • July 2019
  • October 2018
  • May 2018
  • February 2018
  • June 2017
  • February 2017
  • November 2016
  • September 2016
  • August 2016
  • May 2016
  • March 2016
  • December 2015
  • September 2015
  • August 2015
  • February 2015
  • January 2015
  • November 2014
  • October 2014
  • September 2014
  • July 2014
  • June 2014
  • January 2014
  • October 2013
  • September 2013
  • March 2013
  • February 2013
  • January 2013
  • December 2012
  • October 2012
  • September 2012
  • August 2012
  • July 2012
  • June 2012
  • January 2012
  • September 1816