Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice
  2. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

Trajectory prediction for 2D game

Discussion in 'Scripting' started by RetronamicGames, Sep 26, 2013.

  1. RetronamicGames

    RetronamicGames

    Joined:
    Feb 9, 2013
    Posts:
    84
    I'm working on a slingshot physics game and i'm looking for a solution to calculate, and display, a dotted line with the predicted trajectory of my slingshotted item. I started using this: http://wiki.unity3d.com/index.php?title=Trajectory_Simulation, but it's not very useful for physics-based items.

    Any ideas of how to predict an object trajectory, based on the physics force applied to it? Just like in Peggle or Angry Birds.
     
  2. AlwaysSunny

    AlwaysSunny

    Joined:
    Sep 15, 2011
    Posts:
    260
    This is a non-trivial issue, I'm afraid. Pretty straightforward, however, so if you've got a mind for math and physics, it should be relatively simple. Drawing a curved line is an issue unto itself, but once you've got a handy dandy method for solving the equation(s), you can use that with a varying T to predict future positions. The kinematic equations on this page are what you need: http://www.physicsclassroom.com/class/1dkin/u1l6a.cfm

    I think the only one you need is this one, and you'll need to run it twice:
    D = Vi * T + 1/2 * A * T^2

    Once for the X component of D, you'll have A = 0, and use the X component of Vi
    Again for the Y component of D, you'll have A = gravity, and use the Y component of Vi

    D is displacement, so combining the resultant X and Y components into a Vector2 will give the predicted position at time T.

    Vi is initial velocity (which you can calculate by knowing the slingshot projectile's mass and the impulse force you'll be giving it upon releasing the sling, since (F=MA), (A=F/M), or in this case (Vi = Impulse Force / Projectile Mass).

    T as mentioned is time, so what you're doing to create a trajectory prediction line is taking multiple samples with a varying T, starting at T = 0. Increment T in a loop by discrete steps. The step distance and number of steps will determine overall accuracy and the prediction line's length. You want to wind up with an array of Vector2s which you can then use as points for drawing a curved line.

    Oh, right, and you'll be adding the slingshot projectile's initial position to each value of D so the line's starting point will match the projectile's current position instead of the world origin.
     
    Last edited: Sep 27, 2013