Created
June 29, 2018 23:54
-
-
Save kalineh/c9874137720976edf37844070bb4854a to your computer and use it in GitHub Desktop.
Airfoil.cs
This file contains hidden or 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; | |
using DG.Tweening; | |
public class Airfoil | |
: MonoBehaviour | |
{ | |
[Range(0.0f, 5.0f)] | |
public float liftCoefficient = 1.0f; | |
[Range(0.0f, 5.0f)] | |
public float dragCoefficient = 0.25f; | |
// used to superficially decrease thrust | |
[ReadOnly] | |
public float thrustOffset = 0.0f; | |
[Range(0.5f, 4.0f)] | |
public float velocitySquareFactor = 2.0f; | |
// 0.0f = flat plane, so when flying into wind there is 0 drag | |
// 1.0f = cube, so when flying into the wind there is still 100% drag, in addition to lift | |
public float aerodynamicRatio = 0.3f; | |
private Rigidbody targetBody = null; | |
public void OnEnable() | |
{ | |
targetBody = GetComponent<Rigidbody>(); | |
} | |
public void FixedUpdate() | |
{ | |
var wind = Vector3.zero; | |
var velocity = targetBody.velocity; | |
var velocityDir = targetBody.velocity.SafeNormalize(); | |
var velocityLen = targetBody.velocity.SafeMagnitude(); | |
var velocitySq = Mathf.Pow(velocityLen, velocitySquareFactor); | |
var windRelative = wind - targetBody.velocity; | |
var windRelativeDir = windRelative.SafeNormalize(); | |
var windRelativeForce = windRelative.SafeMagnitude(); | |
var windRelativeForceSq = windRelativeForce * windRelativeForce; | |
var coeffDrag = Mathf.Abs(Vector3.Dot(targetBody.transform.up, velocityDir)); | |
var coeffLift = -Vector3.Dot(targetBody.transform.up, velocityDir); | |
var dragDirection = -velocityDir; | |
coeffDrag = Mathf.Max(coeffDrag, aerodynamicRatio); | |
// handle thrusting | |
coeffLift = coeffLift * Mathf.Lerp(1.0f, 0.6f, thrustOffset); | |
coeffDrag = coeffDrag * Mathf.Lerp(1.0f, 0.6f, thrustOffset); | |
// i know not physically correct, but feels good in-game | |
var liftDirection = targetBody.transform.up; | |
var liftForce = coeffLift * liftDirection * velocitySq * liftCoefficient; | |
var dragForce = coeffDrag * dragDirection * velocitySq * dragCoefficient; | |
targetBody.AddForce(liftForce, ForceMode.Acceleration); | |
targetBody.AddForce(dragForce, ForceMode.Acceleration); | |
//Debug.DrawLine(transform.position, transform.position + liftForce * 5.0f, Color.green, 0.1f); | |
//Debug.DrawLine(transform.position, transform.position + dragForce * 5.0f, Color.red, 0.1f); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment