using System.Collections; using System.Collections.Generic; using UnityEngine; public class BulletVelocityTrajectoryPredictor : MonoBehaviour { public float speed; //speed of bullet public Vector3 startPosition; //starting position of bullet public Vector3 direction; //direction of bullet public int lineSegmentCount = 10; //number of segments in trajectory line public LineRenderer lineRenderer; //LineRenderer component // Use this for initialization void Start () { lineRenderer.positionCount = lineSegmentCount; PredictTrajectory(); } // Update is called once per frame void Update () { PredictTrajectory(); } //Predicts trajectory of bullet void PredictTrajectory() { Vector3 velocity = speed * direction; //velocity of bullet Vector3 previousPosition = startPosition; for (int i = 0; i < lineSegmentCount; i++) { //Predict next position float time = (float)i / (lineSegmentCount - 1); Vector3 nextPosition = CalculatePositionAtTime(time, startPosition, velocity); //Draw line segment lineRenderer.SetPosition(i, nextPosition); //Update previous position previousPosition = nextPosition; } } //Calculates position at given time Vector3 CalculatePositionAtTime(float time, Vector3 startPosition, Vector3 velocity) { //Calculate gravity vector Vector3 gravity = Physics.gravity; //Calculate position Vector3 position = startPosition + time * velocity + 0.5f * gravity * Mathf.Pow(time, 2); return position; } }
Preview:
downloadDownload PNG
downloadDownload JPEG
downloadDownload SVG
Tip: You can change the style, width & colours of the snippet with the inspect tool before clicking Download!
Click to optimize width for Twitter