create a unity script bullet velocity trajectory predictor Line with LineRendererJobs.
Tue Dec 06 2022 18:24:08 GMT+0000 (Coordinated Universal Time)
Saved by
@Ezio727
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;
}
}
content_copyCOPY
Comments