How would one go about implementing Unreal's Suggest Projectile Velocity function in Unity?
in UE4 there's a function called SuggestProjectileVelocity which will as expected give you a direction to launch a projectile given a start location, end location, gravity, speed, and whether you want a low or high arc. I believe it also tells you if there's no solution available.
How would one go about doing this?
Answer by apapineni · Jan 21, 2021 at 11:09 AM
So I ended up figuring this out. Could probably use some cleaning up but this is the function I am using.
private Vector3 GetLaunchVelocity(Vector3 startPos, Vector3 targetPos, float speed, bool highArc)
{
Vector3 launchVelocity = Vector3.zero;
Vector3 deltaPosition = targetPos - startPos;
Vector3 horizontalDeltaPos = new Vector3(deltaPosition.x, 0, deltaPosition.z);
Vector3 rotatedDeltaPosition = new Vector3(horizontalDeltaPos.magnitude, deltaPosition.y, 0);
float angle1 = (180.0f / Mathf.PI) * Mathf.Atan((speed * speed + Mathf.Sqrt(Mathf.Pow(speed, 4) - Physics.gravity.magnitude * (Physics.gravity.magnitude * rotatedDeltaPosition.x * rotatedDeltaPosition.x + 2 * rotatedDeltaPosition.y * speed * speed))) / (Physics.gravity.magnitude * rotatedDeltaPosition.x));
float angle2 = (180.0f / Mathf.PI) * Mathf.Atan((speed * speed - Mathf.Sqrt(Mathf.Pow(speed, 4) - Physics.gravity.magnitude * (Physics.gravity.magnitude * rotatedDeltaPosition.x * rotatedDeltaPosition.x + 2 * rotatedDeltaPosition.y * speed * speed))) / (Physics.gravity.magnitude * rotatedDeltaPosition.x));
float minAngle = Mathf.Min(angle1, angle2);
float maxAngle = Mathf.Max(angle1, angle2);
float angle = highArc ? maxAngle : minAngle;
if (!float.IsNaN(angle))
{
launchVelocity = Quaternion.AngleAxis(angle, Vector3.Cross(horizontalDeltaPos, Vector3.up)) * horizontalDeltaPos.normalized * speed;
}
return launchVelocity;
}
Your answer
Follow this Question
Related Questions
Why my gravity direction is rotating with transform.rotation? 1 Answer
How to apply a force at certain point of an object? 0 Answers
[Help] Player stops moving when hitting wall diagonally 0 Answers
What about physics happening far from the (floating) origin ? 0 Answers
RigidBody MovePosition lags behind another RigidBody 1 Answer