Physics Maths

Heathen.UnityPhysics.API.Maths is a static library of physics maths for gameplay code. It is built on Unity.Mathematics types (float3, float2, quaternion) and works with Burst. The methods are pure maths and never log. Rigidbody versions take a Rigidbody and read what they need from it.

using Heathen.UnityPhysics.API;

Intercept #

Find where an interceptor of a given speed meets a moving target.

MethodWhat it does
SafeIntercept(position, speed, targetPosition, targetVelocity)The point where an interceptor of the given speed meets a target moving at constant velocity, as float3?. Exact, and returns null when there is no intercept (for example a target that is faster than the interceptor and moving away). Overloads take a Rigidbody target, or a heading and speed in place of a velocity.
FastIntercept(...)A cheaper estimate that assumes the interceptor is much faster than the target. It does not detect the no-solution case, so use SafeIntercept when that can happen. Same overloads.
InterceptTime(speed, relativePosition, targetVelocity)Solves the earliest positive time at which the interceptor can meet the target: the smallest t above zero where the distance equals speed x t.
float3? hit = Maths.SafeIntercept(shooter.position, projectileSpeed, target.position, targetVelocity);
if (hit.HasValue)
    Aim(hit.Value);

Drag and wind #

MethodWhat it does
QuadraticDrag(dragCoefficient, fluidDensity, flowVelocity, area)The drag force of a fluid flowing past an object: 0.5 x Cd x density x area x speed squared. flowVelocity is the velocity of the fluid relative to the object (the wind velocity minus the object velocity), and the returned force acts on the object along that flow.
QuadraticDrag(dragCoefficient, fluidDensity, speed, area)The scalar force magnitude for a speed through a fluid.
SimulateWindForce(main, frequency, magnitude, turbulence, direction, gameTime)A dynamic wind vector: a steady main strength with gusts at frequency cycles per second swinging by magnitude, and a direction that wanders up to 30 degrees either side about the up axis at the turbulence rate (zero disables it). Pass the current time to animate it.
FallDistance(gravity, time)The distance an object falls in a time under a gravity.

Forces and torques to reach a goal #

These return the force or torque that reaches a goal within one fixed update, for you to apply to the Rigidbody. Apply the result with ForceMode.Force.

MethodWhat it does
ForceToReachLinearVelocity(body, targetVelocity)The force to reach a target velocity in one fixed update.
ForceToReachAngularVelocity(body, targetAngularVelocity)The torque to reach a world-space angular velocity (radians per second), using the body’s inertia tensor and rotation.
TorqueToReachDirection(body, targetDirection)The torque that turns the body so its forward vector points along a direction.
TorqueToReachDirection2D(body2D, targetDirection)The 2D version, so the body’s right vector points along a direction. Works in radians even though Rigidbody2D.angularVelocity is degrees per second.
TorqueToReachRotation(body, targetRotation)The torque that turns the body’s forward to match a target rotation’s forward.
LerpTo(...)Constant-rate movement. Overloads move a position at a speed over a time step, rotate a rotation at degrees per second, return the force to accelerate a Rigidbody toward a target velocity at an acceleration, or the torque to rotate it toward a target rotation at a speed.
Acceleration(mass, force), Acceleration2DNewton’s second law, a = F / m.
ElasticityAcceleration(mass, displacement, elasticity), ElasticityAcceleration2DHooke’s law: a restoring acceleration that opposes the displacement.
Torque(force, position, pivot), Torque2DThe torque of a force applied at a position about a pivot (lever arm cross force). The 2D version is the scalar z torque, positive counter-clockwise.
WorldInertia(body), WorldInertia(principalMoments, rotation)The 3×3 world-space inertia tensor of a body, or built from principal moments and the rotation of the principal axes.

Rotations and directions #

MethodWhat it does
RotationVectorBetween(from, to, fallbackAxis)The rotation vector (axis scaled by angle in radians) that turns one direction onto another by the shortest path. Correct across the full 0 to 180 degree range. When the directions are exactly opposed the axis is taken from fallbackAxis.
SignedAngle2D(from, to)The signed angle in radians (-pi to pi) from one 2D direction to another, positive counter-clockwise, zero when either has no length.
LookRotation(direction)The rotation that looks along a direction, identity when it has no length.
QuaternionDifference(from, to), QuaternionSum(from, quantity)The rotation that takes one rotation to another, and the result of applying a rotation to a starting rotation.
RotatePointAroundPivot(point, pivot, angles or rotation)Rotates a point around a pivot by Euler angles in degrees or by a quaternion.
GetForwardDirection, GetBackDirection, GetRightDirection, GetLeftDirection, GetUpDirection, GetDownDirection (rotation)The world direction an axis points after a rotation. GetForwardDirection(Quaternion) returns the forward vector.

Geometry #

MethodWhat it does
NearestPointOnLineSegment(start, end, point)The nearest point on a segment. A zero-length segment returns its start point.
NearestPointOnLine(start, direction, point)The nearest point on a line with no ends.
CircleContains, SphereContains, EllipseContains, EllipsoidContainsWhether a point is inside or on a circle, sphere, ellipse or ellipsoid.
GetPointOnCircle(center, radius, angle), GetPointOnEllipse(...)A point on the perimeter at an angle in degrees, where 0 is the positive X axis.
ScreenSizeAtDistance(camera, distance)The full height of a camera’s view at a distance.
ScalarByDistance(camera, naturalDistance, testDistance)The scale an object needs at one distance to appear the same size as at another.
ValidateNaN(value)Replaces NaN with zero, for a float, float2 or float3 (each NaN component).

Polynomial solvers #

Ported from Graphics Gems, returning the number of real roots found and the roots as out values.

MethodSolves
SolveQuadric(c0, c1, c2, out s0, out s1)c0 x^2 + c1 x + c2 = 0, up to two roots.
SolveCubic(c0, c1, c2, c3, out s0, out s1, out s2)c0 x^3 + c1 x^2 + c2 x + c3 = 0 by Cardano’s method, up to three roots.
SolveQuartic(c0, c1, c2, c3, c4, out s0, out s1, out s2, out s3)c0 x^4 + … + c4 = 0, up to four roots.

The leading coefficient must be non-zero for each solver. All of them take double for precision.

Verlet integration #

MethodWhat it does
SimpleVerletIntegration(currentPosition, priorPosition, acceleration, timestep)A fixed-step Verlet step for a particle.
TimeCorrectedVerletIntegration(currentPosition, priorPosition, inertia, acceleration, scale, currentTimestep, priorTimestep)A Verlet step that corrects for a variable time step, which keeps simulations stable. inertia is the fraction of velocity kept (0 to less than 1, values of 1 or more cause instability).
TimeCorrectedVerletIntegration2D(...)The 2D version.

Toolkit for Verlet Motion is a separate, standalone package, see the Verlet article.

Rate This Article!