-
Notifications
You must be signed in to change notification settings - Fork 2
/
TrajectoryController.cs
100 lines (80 loc) · 2.35 KB
/
TrajectoryController.cs
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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class TrajectoryController : MonoBehaviour
{
[Header("Line renderer veriables")]
public LineRenderer line;
[Range(2, 30)]
public int resolution;
[Header("Formula variables")]
public Vector2 velocity;
public float yLimit;
private float g;
[Header("Linecast variables")]
[Range(2, 30)]
public int linecastResolution;
public LayerMask canHit;
private void Start()
{
g = Mathf.Abs(Physics2D.gravity.y);
}
private void Update()
{
RenderArc();
}
private void RenderArc()
{
line.positionCount = resolution + 1;
line.SetPositions(CalculateLineArray());
}
private Vector3[] CalculateLineArray()
{
Vector3[] lineArray = new Vector3[resolution + 1];
var lowestTimeValue = MaxTimeX() / resolution;
for (int i = 0; i < lineArray.Length; i++)
{
var t = lowestTimeValue * i;
lineArray[i] = CalculateLinePoint(t);
}
return lineArray;
}
private Vector2 HitPosition()
{
var lowestTimeValue = MaxTimeY() / linecastResolution;
for (int i = 0; i < linecastResolution + 1; i++)
{
var t = lowestTimeValue * i;
var tt = lowestTimeValue * (i + 1);
var hit = Physics2D.Linecast(CalculateLinePoint(t), CalculateLinePoint(tt), canHit);
if (hit)
return hit.point;
}
return CalculateLinePoint(MaxTimeY());
}
private Vector3 CalculateLinePoint(float t)
{
float x = velocity.x * t;
float y = (velocity.y * t) - (g * Mathf.Pow(t, 2) / 2);
return new Vector3(x + transform.position.x, y + transform.position.y);
}
private float MaxTimeY()
{
var v = velocity.y;
var vv = v * v;
var t = (v + Mathf.Sqrt(vv + 2 * g * (transform.position.y - yLimit))) / g;
return t;
}
private float MaxTimeX()
{
var x = velocity.x;
if(x == 0)
{
velocity.x = 000.1f;
x = velocity.x;
}
var t = (HitPosition().x - transform.position.x) / x;
return t;
}
}