64 lines
2.2 KiB
C#
64 lines
2.2 KiB
C#
using System.Collections;
|
||
using System.Collections.Generic;
|
||
using UnityEngine;
|
||
|
||
public class ArcPrediction : MonoBehaviour
|
||
{
|
||
LineRenderer lr;
|
||
const int MAX_RENDER_LENGHT = 1000;
|
||
|
||
private void Awake()
|
||
{
|
||
lr = GetComponent<LineRenderer>();
|
||
}
|
||
|
||
//initialization
|
||
public void RenderArc(float velocity, int resolution, Vector3 rotation)
|
||
{
|
||
var prediction = CalculateArcArray(velocity, resolution, rotation);
|
||
lr.startWidth = 0.005f;
|
||
lr.endWidth = lr.startWidth * Mathf.Sqrt(Vector3.Distance(prediction[0], prediction[prediction.Length-1]));// valeurs exp<78>rimental
|
||
lr.positionCount = prediction.Length;
|
||
lr.SetPositions(prediction);
|
||
}
|
||
|
||
public void HideArc()
|
||
{
|
||
lr.startWidth = lr.endWidth = 0;
|
||
}
|
||
|
||
//Create an array of Vector 3 positions for the arc
|
||
Vector3[] CalculateArcArray(float velocity, int resolution, Vector3 rotation)
|
||
{
|
||
Vector3[] arcArray = new Vector3[MAX_RENDER_LENGHT];
|
||
Vector3 velocityVector = rotation * velocity;
|
||
arcArray[0] = transform.parent.position;
|
||
int validSegments = 0;
|
||
for (int i = 1; i < MAX_RENDER_LENGHT; i++)
|
||
{
|
||
//Figure out next position
|
||
float t = (float)i / (float)resolution;
|
||
Vector3 horizontalMovement = new Vector3(velocityVector.x, 0, velocityVector.z) * t;
|
||
Vector3 verticalDirection = new Vector3(0, t * velocityVector.y + 0.5f * Physics.gravity.y * Mathf.Pow(t, 2), 0);
|
||
var result = horizontalMovement + verticalDirection + transform.parent.position;
|
||
arcArray[i] = result;
|
||
|
||
//Figure out if the prediction should stop based on hitting an object
|
||
RaycastHit hit;
|
||
validSegments++;
|
||
if (Physics.Linecast(arcArray[i - 1], arcArray[i], out hit))
|
||
{
|
||
arcArray[i] = hit.point;
|
||
break;
|
||
}
|
||
}
|
||
//IDK why this version of unity doesn't have a sub-array creation function, or at least why VisualStudio wasn't suggesting it
|
||
Vector3[] output = new Vector3[validSegments+1];
|
||
for(int i = 0; i <= validSegments; i++)
|
||
{
|
||
output[i] = arcArray[i];
|
||
}
|
||
return output;
|
||
}
|
||
}
|