Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- FVector ULowLevelBirdMathFunctionLibrary::SuggestProjectileVelocityFromPeakHeight(const UObject* WorldContext, FVector startPos, FVector endPos, double overrideGravityZ, double peakHeight)
- {
- // First, convert the 3D point to point into the equivalent 2D math. That's how all the ballistic equations are written! Don't make this harder than need be!
- FVector displacement3D = endPos - startPos;
- float displacementDistance = (displacement3D.X * displacement3D.X) + (displacement3D.Y * displacement3D.Y);
- if (!ensureMsgf(displacementDistance > 0.001, TEXT("distance travelled must be non-zero"))) { return FVector(0, 0, 0); }
- FVector displacementDirection = FVector(displacement3D.X, displacement3D.Y, 0);
- displacementDirection.Normalize();
- displacementDistance = sqrt(displacementDistance);
- FVector2D displacement = FVector2D(displacementDistance, displacement3D.Z);
- if (!ensureMsgf(peakHeight > 0.0, TEXT("peakHeight must be higher than the starting position"))) { return FVector(0, 0, 0); }
- if (!ensureMsgf(peakHeight > displacement.Y, TEXT("peakHeight must be higher than the end position"))) { return FVector(0, 0, 0); }
- // Extract the current world gravity (assuming we can), and override if necessary
- double gravity = 0;
- if (WorldContext != NULL) { gravity = WorldContext->GetWorld()->GetGravityZ(); }
- if (overrideGravityZ != 0) { gravity = overrideGravityZ; }
- // Now do the fancy math (care of @Rich in channel) to calculate the launch velocity necessary to meet the given parameters
- FVector2D launchVelocity;
- launchVelocity = FVector2D::ZeroVector;
- launchVelocity.Y = FMath::Sqrt(-2.0f * gravity * peakHeight);
- double fallDisp = displacement.Y - peakHeight;
- double invG = 1.0f / gravity;
- double tPeak = -launchVelocity.Y * invG; // Peak Time
- double tFall = FMath::Sqrt(2 * fallDisp * invG);
- double tTotal = tPeak + tFall; // Target Time
- launchVelocity.X = displacement.X / tTotal;
- // Done! Now convert it back into 3D space, and return
- FVector launchVelocity3D;
- launchVelocity3D.X = displacementDirection.X * launchVelocity.X;
- launchVelocity3D.Y = displacementDirection.Y * launchVelocity.X;
- launchVelocity3D.Z = launchVelocity.Y;
- return launchVelocity3D;
- }
Advertisement
Add Comment
Please, Sign In to add comment