Created
March 30, 2016 00:40
-
-
Save marcelschmidtdev/e46d166b639c06af3ba896fcb8412be4 to your computer and use it in GitHub Desktop.
A simple throw parable for Unity
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 UnityEngine; | |
using System.Collections; | |
public class Parable : MonoBehaviour | |
{ | |
public Transform Target; | |
public float firingAngle = 45.0f; | |
public float gravity = 9.8f; | |
public Transform Projectile; | |
private Transform myTransform; | |
void Awake() | |
{ | |
myTransform = transform; | |
} | |
void Start() | |
{ | |
StartCoroutine(SimulateProjectile()); | |
} | |
IEnumerator SimulateProjectile() | |
{ | |
// Short delay added before Projectile is thrown | |
yield return new WaitForSeconds(1.5f); | |
// Move projectile to the position of throwing object + add some offset if needed. | |
Projectile.position = myTransform.position + new Vector3(0, 0.0f, 0); | |
// Calculate distance to target | |
float target_Distance = Vector3.Distance(Projectile.position, Target.position); | |
// Calculate the velocity needed to throw the object to the target at specified angle. | |
float projectile_Velocity = target_Distance / (Mathf.Sin(2 * firingAngle * Mathf.Deg2Rad) / gravity); | |
// Extract the X & Y componenent of the velocity | |
float Vx = Mathf.Sqrt(projectile_Velocity) * Mathf.Cos(firingAngle * Mathf.Deg2Rad); | |
float Vy = Mathf.Sqrt(projectile_Velocity) * Mathf.Sin(firingAngle * Mathf.Deg2Rad); | |
// Calculate flight time. | |
float flightDuration = target_Distance / Vx; | |
// Rotate projectile to face the target. | |
Projectile.rotation = Quaternion.LookRotation(Target.position - Projectile.position); | |
float elapse_time = 0; | |
while (elapse_time < flightDuration) | |
{ | |
Projectile.Translate(0, (Vy - (gravity * elapse_time)) * Time.deltaTime, Vx * Time.deltaTime); | |
elapse_time += Time.deltaTime; | |
yield return null; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment