# Question Unity 2D, Display Trajectory of project not working

Discussion in 'Physics' started by James_Neville, Nov 25, 2022.

1. ### James_Neville

Joined:
Dec 29, 2021
Posts:
1
Code (CSharp):
1. void DrawTrajectory()
2.     {
3.         lr.positionCount = SimulateArc().Count;    //Optimization: At some point, just pass _launchDir and _dist through as method arguments? For now keep global
4.         for (int a = 0; a < lr.positionCount; a++)
5.         {
6.             lr.SetPosition(a, SimulateArc()[a]); //Add each Calculated Step to a LineRenderer to display a Trajectory. Look inside LineRenderer in Unity to see exact points and amount of them
7.         }
8.     }
9.
10.     private List<Vector2> SimulateArc()
11.     {
12.         List<Vector2> trajectoryPoints = new List<Vector2>(); //Reset trajectoryPoints List to make a new one
13.
14.         float simulateForDuration = 5f;//INPUT amount of total time for simulation
15.         float simulationStep = 0.1f;//INPUT amount of time between each position check
16.
17.
18.         Vector2 launchPosition = thrownWeaponStartPos.position; //INPUT launch position (Important to make sure RayCast is ignoring some layers (easiest to use default Layer 2))
19.
20.         Touch touch = Input.GetTouch(0);
21.         Vector2 directionVector = -(launchPosition - (Vector2)Camera.main.ScreenToViewportPoint(touch.position)).normalized * 100; //INPUT launch direction (This Vector2 is automatically normalized for us, keeping it in low and communicable terms)
22.
23.         int steps = (int)(simulateForDuration / simulationStep);//Calculates amount of steps simulation will iterate for
24.         float vel = throwingSpeed / thrownMass * Time.fixedDeltaTime; //Velocity = Force / Mass * time
25.
26.         for (int i = 0; i < steps; ++i) //Iterate a ForLoop over number of Steps
27.         {
28.             //Remember f(t) = (x0 + x*t, y0 + y*t - 9.81t²/2)
29.             //To calculate new Position at each Step... Origin + (LaunchDirection * (LaunchSpeed * Current Step * Length of a Step)
30.             Vector2 calculatedPosition = launchPosition + (directionVector * vel * i * simulationStep); //Calculate new Vector at flat speed
31.             calculatedPosition.y += Physics2D.gravity.y / 2 * Mathf.Pow((i * simulationStep), 2); //Factor in Gravity, affecting only the Y-Axis (y0 + y*t - 9.81t²/2)
32.