The Math package provides essential mathematical utilities for 3D graphics and game development. It includes three main classes that handle different aspects of mathematical operations:
| Class | Purpose |
|---|---|
| MathF | General mathematical utilities and operations |
| Vector | 3D vector mathematics and transformations |
| Matrix4 | 4x4 matrix operations for 3D transformations |
// Create world transform
Matrix4 translation = Matrix4.translate(new Vector(1, 2, 3));
Matrix4 rotation = Matrix4.rotate(45, new Vector(0, 1, 0));
Matrix4 scale = Matrix4.scale(new Vector(2, 2, 2));
// Combine transforms
Matrix4 worldMatrix = Matrix4.multiply(translation,
Matrix4.multiply(rotation, scale));
// Transform a point
Vector point = new Vector(1, 0, 0);
Vector transformed = point.transform(worldMatrix);// Basic vector math
Vector a = new Vector(1, 0, 0);
Vector b = new Vector(0, 1, 0);
Vector sum = a.add(b);
Vector diff = a.sub(b);
float dot = a.dot(b);
Vector cross = a.cross(b);
// Normalization
Vector dir = b.sub(a).normal();// Linear interpolation
float t = 0.5f;
float value = MathF.lerp(0, 100, t);
Vector pos = Vector.lerp(startPos, endPos, t);-
Use appropriate data types:
Vectorfor positions, directions, and normalsMatrix4for transforms and projectionsMathFfor general mathematical operations
-
Performance optimization:
- Cache frequently used calculations
- Use
sqMagnitude()instead ofmagnitude()for comparisons - Minimize matrix operations in tight loops
-
Numerical stability:
- Normalize vectors after transformations
- Check for division by zero
- Use
clamp()for bounded values
-
Memory management:
- Reuse vectors and matrices when possible
- Use in-place operations when appropriate
- Cache transform matrices that don't change often
The Math package integrates with various engine systems:
-
Transform Component
- Uses
Matrix4for world transforms - Uses
Vectorfor position, rotation, scale
- Uses
-
Camera System
- Uses
Matrix4for view and projection matrices - Uses
Vectorfor camera position and direction
- Uses
-
Physics System
- Uses
Vectorfor velocities and forces - Uses
MathFfor interpolation and clamping
- Uses
-
Graphics Pipeline
- Uses
Matrix4for MVP (Model-View-Projection) matrices - Uses
Vectorfor vertices and normals
- Uses
// Create camera matrices
float fov = 60.0f;
float aspect = width / height;
Matrix4 projection = Matrix4.perspective(fov, aspect, 0.1f, 1000.0f);
Vector eye = new Vector(0, 5, -10);
Vector target = new Vector(0, 0, 0);
Vector up = new Vector(0, 1, 0);
Matrix4 view = createViewMatrix(eye, target, up);// Smooth movement
Vector currentPos = object.getPosition();
Vector targetPos = new Vector(10, 0, 0);
float maxDelta = 0.1f;
// Update each frame
float x = MathF.moveTowards(currentPos.x, targetPos.x, maxDelta);
float y = MathF.moveTowards(currentPos.y, targetPos.y, maxDelta);
float z = MathF.moveTowards(currentPos.z, targetPos.z, maxDelta);
object.setPosition(new Vector(x, y, z));