[Unity] Projectile equation: trajectory prediction

Today, I implemented a projectile equation to get a trajectory prediction. It doesn't take care of weight, wind and drag, but it cover enough the basis.





The script is ready to use.


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
using UnityEngine;
using System.Collections.Generic;

public class ProjectileEquation
{
    [SerializeField]
    public static Vector3 s_StartVelocity = Vector3.zero;
    [SerializeField]
    public static Vector3 s_StartPosition = Vector3.zero;

    /// <summary>
    /// Get X
    /// </summary>
    /// <param name="t">Time</param>
    /// <returns>X coordinate at t time</returns>
    private static float GetX(float t)
    {
        return s_StartVelocity.x * t + s_StartPosition.x;
    }

    /// <summary>
    /// Get Y
    /// </summary>
    /// <param name="t">Time</param>
    /// <returns>Y coordinate at t time</returns>
    private static float GetY(float t)
    {
        return 0.5f * Physics.gravity.y * t * t + s_StartVelocity.y * t + s_StartPosition.y;
    }

    /// <summary>
    /// Get Z
    /// </summary>
    /// <param name="t">Time</param>
    /// <returns>Z coordinate at t time</returns>
    private static float GetZ(float t)
    {
        return s_StartVelocity.z * t + s_StartPosition.z;
    }

    /// <summary>
    /// Get trajectory
    /// </summary>
    /// <param name="startPosition">Start position</param>
    /// <param name="velocity">Start velocity</param>
    /// <param name="tMax">Max t</param>
    /// <param name="tStep">Time step</param>
    /// <returns>Trajectory</returns>
    public static List<Vector3> GetTrajectory(Vector3 position, Vector3 velocity, float tMax, float tStep)
    {
        // Keep values
        s_StartPosition = position;
        s_StartVelocity = velocity;

        // Init list
        List<Vector3> trajectory = new List<Vector3>();

        // Fill list
        for (float t = 0; t < tMax; t += tStep)
        {
            trajectory.Add(new Vector3(GetX(t), GetY(t), GetZ(t)));
        }

        return trajectory;
    }
}  

Comments

Popular posts from this blog

[Unity][Shader] Night Vision

[FPS Maker] Custom FPS Game Engine

[UE4][Shader] Post process: tresholded black and white with sobel edge