Created
February 8, 2018 03:06
-
-
Save calderarchinuk/7487e171762497c1a21009ad96ca5102 to your computer and use it in GitHub Desktop.
calculate and render an arc affected by gravity
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System.Collections; | |
using System.Collections.Generic; | |
using UnityEngine; | |
public class ArcRender : MonoBehaviour | |
{ | |
public int Count = 10; | |
public float PowerMultiplier = 2; | |
public Transform handle; | |
float GravityAmount = -9.81f; | |
float FixedTimestep = 0.01f; | |
LineRenderer lineRenderer; | |
void Start () | |
{ | |
if (handle == null) | |
{ | |
Debug.LogWarning("handle is just for getting the direction vector"); | |
var go = new GameObject("handle"); | |
go.transform.position = transform.position + new Vector3(-1,-1,-1); | |
handle = go.transform; | |
} | |
lineRenderer = GetComponent<LineRenderer>(); | |
if (lineRenderer) | |
{ | |
lineRenderer.useWorldSpace = true; | |
lineRenderer.positionCount = Count; | |
} | |
FixedTimestep = Time.fixedDeltaTime; | |
} | |
//the direction and magnitude to draw the line | |
public Vector3 GetDirectionVector() | |
{ | |
return (transform.position - handle.position) * PowerMultiplier; | |
} | |
//draw debug rays and update line renderer | |
void Update () | |
{ | |
var positions = GetPositions(Count); | |
for(int i = 0;i<positions.Count-1;i++) | |
{ | |
Debug.DrawLine(positions[i],positions[i+1],Color.green); | |
} | |
if (lineRenderer != null) | |
{ | |
lineRenderer.SetPositions(positions.ToArray()); | |
} | |
} | |
public List<Vector3> GetPositions(int positionCount) | |
{ | |
List<Vector3> arcPositions = new List<Vector3>(); | |
Vector3 vector = GetDirectionVector() * FixedTimestep; | |
Vector3 gravityvector = Vector3.up * GravityAmount; | |
Vector3 lastVector = vector; | |
Vector3 lastPosition = transform.position; | |
arcPositions.Add(lastPosition); | |
for(int i = 0; i< positionCount;i++) | |
{ | |
//Debug.DrawRay(lastPosition,lastVector,Color.red); | |
lastPosition += lastVector; | |
lastVector += gravityvector * FixedTimestep; | |
arcPositions.Add(lastPosition); | |
} | |
return arcPositions; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment