MathHelper
Static class with common math utilities and constants.
using Xengine.Math;
Constants
| Constant | Value | Description |
|---|---|---|
MathHelper.PI | 3.14159... | Pi constant |
MathHelper.TwoPI | 6.28318... | 2 * Pi |
MathHelper.HalfPI | 1.57079... | Pi / 2 |
MathHelper.Deg2Rad | 0.01745... | Degrees to radians multiplier |
MathHelper.Rad2Deg | 57.2957... | Radians to degrees multiplier |
MathHelper.Epsilon | 0.00001 | Small value for comparisons |
Methods
Clamp
static float Clamp(float value, float min, float max)
float health = MathHelper.Clamp(health, 0, maxHealth);
Clamp01
static float Clamp01(float value)
Clamps value between 0 and 1.
float t = MathHelper.Clamp01(progress);
Lerp
static float Lerp(float a, float b, float t)
Linear interpolation between a and b.
float value = MathHelper.Lerp(0, 100, 0.5f); // 50
LerpUnclamped
static float LerpUnclamped(float a, float b, float t)
Lerp without clamping t to [0,1].
InverseLerp
static float InverseLerp(float a, float b, float value)
Returns where value lies between a and b (0 to 1).
float t = MathHelper.InverseLerp(0, 100, 25); // 0.25
Remap
static float Remap(float value, float fromMin, float fromMax, float toMin, float toMax)
Remap value from one range to another.
// Convert 0-100 to 0-1
float normalized = MathHelper.Remap(75, 0, 100, 0, 1); // 0.75
SmoothStep
static float SmoothStep(float from, float to, float t)
Smooth interpolation with ease-in/ease-out.
float smooth = MathHelper.SmoothStep(0, 1, t);
MoveTowards
static float MoveTowards(float current, float target, float maxDelta)
Move towards target by at most maxDelta.
health = MathHelper.MoveTowards(health, maxHealth, healRate * Time.Delta);
Repeat
static float Repeat(float t, float length)
Loops value between 0 and length.
float looped = MathHelper.Repeat(time, 5f); // 0 to 5, then back to 0
PingPong
static float PingPong(float t, float length)
Ping-pong value between 0 and length.
float bounce = MathHelper.PingPong(Time.Now, 1f); // 0 to 1 to 0 to 1...
Approximately
static bool Approximately(float a, float b)
Check if two floats are approximately equal.
if (MathHelper.Approximately(distance, 0f))
Log.Info("At destination!");
ToRadians / ToDegrees
float radians = MathHelper.ToRadians(90); // 1.5708
float degrees = MathHelper.ToDegrees(MathHelper.PI); // 180
Common Patterns
Health Bar
float healthPercent = MathHelper.Clamp01((float)health / maxHealth);
float barWidth = MathHelper.Lerp(0, maxBarWidth, healthPercent);
Smooth Animation
float t = MathHelper.PingPong(Time.Now, 1f);
float smooth = MathHelper.SmoothStep(0, 1, t);
position.Y = MathHelper.Lerp(minY, maxY, smooth);
Angle Wrapping
angle = MathHelper.Repeat(angle, 360f); // Keep between 0-360