Every video game you’ve ever played runs on mathematics. From calculating whether a bullet hits its target to determining how light reflects off a surface, geometry formulas are the invisible foundation of game development. Whether you’re creating the next indie hit or learning how to make a video game, understanding these essential formulas will transform you from a beginner to a confident developer.
This comprehensive guide covers all the geometry formulas you’ll actually use in game development, complete with practical code examples and real-world applications. No abstract theory—just the math that makes games work.
Why Geometry Matters in Game Development
Game development is applied geometry. Every frame rendered, every collision detected, and every character movement calculated relies on geometric principles. Unlike academic geometry courses, game development requires you to implement these formulas in code that runs 60 times per second.
The formulas in this guide represent the core mathematical toolkit every game developer needs, from 2D mobile games to complex 3D engines.
Basic 2D Geometry Formulas for Games

Distance Formula
The Formula:
d = √[(x₂ - x₁)² + (y₂ - y₁)²]
Why You Need It: Distance calculation is the most frequently used formula in game development. You’ll use it for collision detection, AI proximity checks, range-based attacks, fog of war systems, and trigger zones.
Code Implementation (C#/Unity):
float Distance(Vector2 point1, Vector2 point2)
{
float dx = point2.x - point1.x;
float dy = point2.y - point1.y;
return Mathf.Sqrt(dx * dx + dy * dy);
}
// Optimized version (avoids expensive square root)
float DistanceSquared(Vector2 point1, Vector2 point2)
{
float dx = point2.x - point1.x;
float dy = point2.y - point1.y;
return dx * dx + dy * dy;
}
Performance Tip: When comparing distances, use squared distance to avoid the expensive square root operation. If you need to check if an enemy is within 10 units, compare squared distance against 100 instead.
Real Example: In a tower defense game, checking if enemies are within turret range happens every frame for every turret. Using DistanceSquared can double your frame rate.
Midpoint Formula
The Formula:
Midpoint = ((x₁ + x₂)/2, (y₁ + y₂)/2)
Why You Need It: Perfect for AI pathfinding waypoints, splitting line segments, camera positioning between two objects, and placing objects between points.
Code Implementation:
Vector2 Midpoint(Vector2 point1, Vector2 point2)
{
return new Vector2(
(point1.x + point2.x) / 2f,
(point1.y + point2.y) / 2f
);
}
Real Example: A co-op game camera that keeps both players in view calculates the midpoint between player positions, then adjusts zoom based on their distance.
Slope and Angle Calculations
The Formulas:
Slope (m) = (y₂ - y₁) / (x₂ - x₁)
Angle (θ) = arctan(m) = arctan((y₂ - y₁) / (x₂ - x₁))
Why You Need It: Aiming systems, projectile trajectories, rotating objects toward targets, and calculating reflection angles.
Code Implementation:
float GetAngleToTarget(Vector2 from, Vector2 to)
{
float dx = to.x - from.x;
float dy = to.y - from.y;
return Mathf.Atan2(dy, dx) * Mathf.Rad2Deg;
}
// Rotate an object to face a target
void FaceTarget(Transform obj, Vector2 target)
{
float angle = GetAngleToTarget(obj.position, target);
obj.rotation = Quaternion.Euler(0, 0, angle);
}
Real Example: Top-down shooters use this to rotate the player character and turrets toward the mouse cursor position.
Point-to-Line Distance
The Formula:
d = |ax₀ + by₀ + c| / √(a² + b²)
where line equation is ax + by + c = 0
Why You Need It: Checking if a character is too close to a wall, laser sight implementations, and pathfinding obstacle avoidance.
Code Implementation:
float PointToLineDistance(Vector2 point, Vector2 lineStart, Vector2 lineEnd)
{
float dx = lineEnd.x - lineStart.x;
float dy = lineEnd.y - lineStart.y;
float numerator = Mathf.Abs(dy * point.x - dx * point.y + lineEnd.x * lineStart.y - lineEnd.y * lineStart.x);
float denominator = Mathf.Sqrt(dx * dx + dy * dy);
return numerator / denominator;
}
Geometry Circle Formulas in Game Development
Circle Area
The Formula:
Area = πr²
Why You Need It: Defining blast radius damage, area-of-effect abilities, circular selection zones, and radar/minimap ranges.
Code Implementation:
float CircleArea(float radius)
{
return Mathf.PI * radius * radius;
}
// Check if point is inside circle (common use case)
bool IsPointInCircle(Vector2 point, Vector2 circleCenter, float radius)
{
float distSquared = (point.x - circleCenter.x) * (point.x - circleCenter.x) +
(point.y - circleCenter.y) * (point.y - circleCenter.y);
return distSquared <= radius * radius;
}
Real Example: An RPG explosion damages all enemies within radius. Instead of checking actual area, you check if each enemy’s distance from explosion center is less than the blast radius.
Circumference
The Formula:
Circumference = 2πr
Why You Need It: Orbital movement paths, circular patrol routes, determining rotation speed, and creating circular patterns.
Code Implementation:
float CircleCircumference(float radius)
{
return 2f * Mathf.PI * radius;
}
// Move object in circular path
Vector2 PointOnCircle(Vector2 center, float radius, float angleInDegrees)
{
float angleRad = angleInDegrees * Mathf.Deg2Rad;
return new Vector2(
center.x + radius * Mathf.Cos(angleRad),
center.y + radius * Mathf.Sin(angleRad)
);
}
Real Example: Satellite objects orbiting a planet, or enemies circling the player at a fixed distance.
Circle-Circle Collision
The Formula:
Collision occurs when: distance between centers ≤ r₁ + r₂
Code Implementation:
bool CirclesColliding(Vector2 center1, float radius1, Vector2 center2, float radius2)
{
float distSquared = (center2.x - center1.x) * (center2.x - center1.x) +
(center2.y - center1.y) * (center2.y - center1.y);
float radiusSum = radius1 + radius2;
return distSquared <= radiusSum * radiusSum;
}
Real Example: Simple collision detection in arcade-style games, bullet-enemy collisions, and pickup item detection.
Triangle Geometry Formulas for 3D Games
Triangle Area (Multiple Methods)
Heron’s Formula:
s = (a + b + c) / 2
Area = √[s(s-a)(s-b)(s-c)]
Base-Height Formula:
Area = (base × height) / 2
Coordinate Formula:
Area = |x₁(y₂ - y₃) + x₂(y₃ - y₁) + x₃(y₁ - y₂)| / 2
Why You Need It: Calculating triangle mesh surface areas, determining polygon winding order, visibility culling, and terrain surface calculations.
Code Implementation:
float TriangleArea(Vector2 p1, Vector2 p2, Vector2 p3)
{
return Mathf.Abs((p1.x * (p2.y - p3.y) +
p2.x * (p3.y - p1.y) +
p3.x * (p1.y - p2.y)) / 2f);
}
// Check if point is inside triangle (barycentric method)
bool IsPointInTriangle(Vector2 point, Vector2 v1, Vector2 v2, Vector2 v3)
{
float totalArea = TriangleArea(v1, v2, v3);
float area1 = TriangleArea(point, v2, v3);
float area2 = TriangleArea(v1, point, v3);
float area3 = TriangleArea(v1, v2, point);
return Mathf.Abs(totalArea - (area1 + area2 + area3)) < 0.001f;
}
Real Example: Click-to-move systems need to determine if the mouse click landed inside a walkable triangle of the navigation mesh.
Triangle Normal Vector (3D)
The Formula:
Normal = (v₂ - v₁) × (v₃ - v₁)
Then normalize the result
Why You Need It: Lighting calculations, surface orientation detection, backface culling, and collision response.
Code Implementation:
Vector3 CalculateNormal(Vector3 v1, Vector3 v2, Vector3 v3)
{
Vector3 edge1 = v2 - v1;
Vector3 edge2 = v3 - v1;
Vector3 normal = Vector3.Cross(edge1, edge2);
return normal.normalized;
}
Real Example: When a character lands on a sloped surface, the normal vector determines which direction is “up” for that surface, affecting character orientation and movement.
Pythagorean Theorem
The Formula:
c² = a² + b²
c = √(a² + b²)
Why You Need It: This is the foundation of the distance formula. Essential for diagonal movement speed correction, right-angle calculations, and 3D distance.
Code Implementation:
// Normalize diagonal movement so it's not faster
Vector2 NormalizeMovement(float horizontal, float vertical)
{
float magnitude = Mathf.Sqrt(horizontal * horizontal + vertical * vertical);
if (magnitude > 1f)
{
return new Vector2(horizontal / magnitude, vertical / magnitude);
}
return new Vector2(horizontal, vertical);
}
Real Example: Without normalization, moving diagonally in a grid-based game would be 1.414x faster than moving horizontally or vertically.
3D Geometry Formulas Essential for Game Development
3D Distance Formula
The Formula:
d = √[(x₂ - x₁)² + (y₂ - y₁)² + (z₂ - z₁)²]
Code Implementation:
float Distance3D(Vector3 point1, Vector3 point2)
{
float dx = point2.x - point1.x;
float dy = point2.y - point1.y;
float dz = point2.z - point1.z;
return Mathf.Sqrt(dx * dx + dy * dy + dz * dz);
}
// Or use built-in
float dist = Vector3.Distance(point1, point2);
Sphere Volume and Surface Area
The Formulas:
Volume = (4/3)πr³
Surface Area = 4πr²
Why You Need It: Bounding sphere collision detection, particle system spawn volumes, spherical force fields, and LOD (level of detail) calculations.
Code Implementation:
float SphereVolume(float radius)
{
return (4f / 3f) * Mathf.PI * radius * radius * radius;
}
float SphereSurfaceArea(float radius)
{
return 4f * Mathf.PI * radius * radius;
}
// Sphere collision detection
bool SpheresColliding(Vector3 center1, float r1, Vector3 center2, float r2)
{
float dist = Vector3.Distance(center1, center2);
return dist <= (r1 + r2);
}
Real Example: Character controllers often use a capsule or sphere for collision rather than complex mesh collision for performance reasons.
Cube/Box Volume and Surface Area
The Formulas:
Volume = length × width × height
Surface Area = 2(lw + lh + wh)
Why You Need It: Bounding box collision (AABB – Axis-Aligned Bounding Box), voxel systems, room/area calculations, and physics optimization.
Code Implementation:
float BoxVolume(Vector3 dimensions)
{
return dimensions.x * dimensions.y * dimensions.z;
}
// AABB collision detection
bool AABBCollision(Vector3 min1, Vector3 max1, Vector3 min2, Vector3 max2)
{
return (min1.x <= max2.x && max1.x >= min2.x) &&
(min1.y <= max2.y && max1.y >= min2.y) &&
(min1.z <= max2.z && max1.z >= min2.z);
}
Real Example: Minecraft-style games use AABB collision for every block. It’s fast enough to check thousands of collisions per frame.
Cylinder Volume
The Formula:
Volume = πr²h
Why You Need It: Character controller capsules, cylindrical trigger zones, and barrel/tube objects.
Code Implementation:
float CylinderVolume(float radius, float height)
{
return Mathf.PI * radius * radius * height;
}
Transformation Formulas: Rotation, Translation, and Scaling
2D Rotation Formula
The Formula:
x' = x cos(θ) - y sin(θ)
y' = x sin(θ) + y cos(θ)
Why You Need It: Rotating sprites, projectile trajectories, camera rotation, and coordinate system transformations.
Code Implementation:
Vector2 RotatePoint(Vector2 point, float angleDegrees)
{
float angleRad = angleDegrees * Mathf.Deg2Rad;
float cos = Mathf.Cos(angleRad);
float sin = Mathf.Sin(angleRad);
return new Vector2(
point.x * cos - point.y * sin,
point.x * sin + point.y * cos
);
}
// Rotate around a specific pivot point
Vector2 RotateAround(Vector2 point, Vector2 pivot, float angleDegrees)
{
Vector2 translated = point - pivot;
Vector2 rotated = RotatePoint(translated, angleDegrees);
return rotated + pivot;
}
Real Example: A top-down shooter rotates the player sprite to face the mouse cursor, then fires bullets in that direction.
3D Rotation (Euler Angles)
The Formulas (around each axis):
X-axis rotation:
y' = y cos(θ) - z sin(θ)
z' = y sin(θ) + z cos(θ)
Y-axis rotation:
x' = x cos(θ) + z sin(θ)
z' = -x sin(θ) + z cos(θ)
Z-axis rotation:
x' = x cos(θ) - y sin(θ)
y' = x sin(θ) + y cos(θ)
Code Implementation:
// Unity handles this with Quaternions for you
transform.Rotate(Vector3.up, 90f); // Rotate 90 degrees around Y axis
// Manual Euler rotation (educational purposes)
Vector3 RotateAroundY(Vector3 point, float angleDegrees)
{
float angleRad = angleDegrees * Mathf.Deg2Rad;
float cos = Mathf.Cos(angleRad);
float sin = Mathf.Sin(angleRad);
return new Vector3(
point.x * cos + point.z * sin,
point.y,
-point.x * sin + point.z * cos
);
}
Important: Modern game engines use Quaternions instead of Euler angles to avoid gimbal lock, but understanding the underlying rotation formulas helps debug orientation issues.
Translation (Movement)
The Formula:
x' = x + dx
y' = y + dy
z' = z + dz
Code Implementation:
Vector3 Translate(Vector3 position, Vector3 movement)
{
return position + movement;
}
// Time-based movement (frame-rate independent)
void Update()
{
float speed = 5f;
Vector3 movement = new Vector3(Input.GetAxis("Horizontal"), 0, Input.GetAxis("Vertical"));
transform.position += movement * speed * Time.deltaTime;
}
Scaling
The Formula:
x' = x × sx
y' = y × sy
z' = z × sz
Code Implementation:
Vector3 Scale(Vector3 point, Vector3 scale)
{
return new Vector3(point.x * scale.x, point.y * scale.y, point.z * scale.z);
}
// Grow object over time
void GrowOverTime()
{
float growthRate = 1.5f;
transform.localScale = Vector3.one * (1 + Time.time * growthRate);
}
Coordinate Geometry Formulas for Game Worlds
Dot Product
The Formula:
A · B = Ax × Bx + Ay × By (+ Az × Bz in 3D)
Alternative:
A · B = |A| × |B| × cos(θ)
Why You Need It: Determining angle between vectors, checking if objects are facing each other, calculating light reflection, and projection calculations.
Code Implementation:
float DotProduct(Vector2 a, Vector2 b)
{
return a.x * b.x + a.y * b.y;
}
// Is target in front of or behind an object?
bool IsInFront(Transform obj, Vector3 target)
{
Vector3 toTarget = (target - obj.position).normalized;
Vector3 forward = obj.forward;
float dot = Vector3.Dot(forward, toTarget);
return dot > 0; // Positive = in front, negative = behind
}
// Is target within field of view cone?
bool IsInFieldOfView(Transform obj, Vector3 target, float fovAngle)
{
Vector3 toTarget = (target - obj.position).normalized;
Vector3 forward = obj.forward;
float dot = Vector3.Dot(forward, toTarget);
float angle = Mathf.Acos(dot) * Mathf.Rad2Deg;
return angle <= fovAngle / 2f;
}
Real Example: Enemy AI uses dot product to detect if the player is within their vision cone. Security cameras in stealth games work the same way.
Cross Product (3D Only)
The Formula:
A × B = (AyBz - AzBy, AzBx - AxBz, AxBy - AyBx)
Why You Need It: Calculating perpendicular vectors, determining winding order (clockwise vs counterclockwise), and computing surface normals.
Code Implementation:
Vector3 CrossProduct(Vector3 a, Vector3 b)
{
return new Vector3(
a.y * b.z - a.z * b.y,
a.z * b.x - a.x * b.z,
a.x * b.y - a.y * b.x
);
}
// Or use built-in
Vector3 cross = Vector3.Cross(a, b);
// Determine which side of a line a point is on
float WhichSide(Vector2 lineStart, Vector2 lineEnd, Vector2 point)
{
Vector2 lineDir = lineEnd - lineStart;
Vector2 toPoint = point - lineStart;
// Fake 3D cross product in 2D (only z component matters)
return lineDir.x * toPoint.y - lineDir.y * toPoint.x;
// Positive = left side, Negative = right side, Zero = on line
}
Real Example: Pathfinding algorithms use cross product to determine if a path curves left or right, helping AI navigate around obstacles.
Advanced Geometry: Interpolation and Curves
Linear Interpolation (Lerp)
The Formula:
result = start + (end - start) × t
where t is between 0 and 1
Why You Need It: Smooth camera movement, animation blending, color transitions, and gradual value changes.
Code Implementation:
float Lerp(float start, float end, float t)
{
return start + (end - start) * t;
}
// Smooth object movement
void SmoothMove(Vector3 target)
{
float speed = 2f;
transform.position = Vector3.Lerp(transform.position, target, Time.deltaTime * speed);
}
// Color fade
Color ColorFade(Color start, Color end, float t)
{
return Color.Lerp(start, end, t);
}
Real Example: Character health bars smoothly decrease using Lerp instead of instantly dropping, making damage feedback more visible to players.
Quadratic Bezier Curve
The Formula:
B(t) = (1-t)²P₀ + 2(1-t)tP₁ + t²P₂
where t is between 0 and 1
Why You Need It: Projectile arcs, camera paths, UI animations, and smooth curved movement.
Code Implementation:
Vector3 QuadraticBezier(Vector3 p0, Vector3 p1, Vector3 p2, float t)
{
float u = 1 - t;
float tt = t * t;
float uu = u * u;
Vector3 point = uu * p0;
point += 2 * u * t * p1;
point += tt * p2;
return point;
}
// Create an arcing projectile
IEnumerator FireArc(Vector3 start, Vector3 end, float height, float duration)
{
Vector3 midPoint = (start + end) / 2f + Vector3.up * height;
float elapsed = 0f;
while (elapsed < duration)
{
float t = elapsed / duration;
transform.position = QuadraticBezier(start, midPoint, end, t);
elapsed += Time.deltaTime;
yield return null;
}
}
Real Example: Grenades, arrows, and basketballs all follow parabolic arcs created with Bezier curves.
Quick Reference: Game Developer’s Formula Cheat Sheet
Distance & Position
| Formula | Use Case | Optimization |
|---|---|---|
d = √[(x₂-x₁)² + (y₂-y₁)²] | 2D distance | Use squared distance for comparisons |
d = √[(x₂-x₁)² + (y₂-y₁)² + (z₂-z₁)²] | 3D distance | Cache frequently used distances |
M = ((x₁+x₂)/2, (y₁+y₂)/2) | Midpoint | Good for camera focus points |
Angles & Rotation
| Formula | Use Case | Note |
|---|---|---|
θ = arctan((y₂-y₁)/(x₂-x₁)) | 2D angle to target | Use Atan2 to avoid division by zero |
x' = x cos(θ) - y sin(θ) | 2D rotation | Combine with translation for orbit |
A · B = |A||B|cos(θ) | Angle between vectors | Great for field of view checks |
Area & Volume
| Formula | Use Case | Performance |
|---|---|---|
A = πr² | Circle area | Common for AOE effects |
A = (base × height)/2 | Triangle area | Foundation of mesh calculations |
V = (4/3)πr³ | Sphere volume | Used in bounding spheres |
V = l × w × h | Box volume | AABB collision standard |
Collision Detection
| Formula | Use Case | Speed |
|---|---|---|
dist ≤ r₁ + r₂ | Circle-circle | Fastest collision check |
AABB overlap | Box-box | Very fast, no rotation |
Point in triangle | Click detection | Medium speed |
Transformations
| Formula | Use Case | Engine Support |
|---|---|---|
P' = P + offset | Translation | Built into all engines |
P' = P × scale | Scaling | Simple multiplication |
Quaternion | 3D rotation | Preferred over Euler angles |
Real Game Examples: Geometry in Action
Example 1: Tower Defense Targeting System
A tower needs to find the closest enemy within range and rotate to face it.
public class TowerController : MonoBehaviour
{
public float range = 10f;
public float rotationSpeed = 5f;
private Transform targetEnemy;
void Update()
{
FindClosestEnemy();
if (targetEnemy != null)
{
RotateTowardsTarget();
}
}
void FindClosestEnemy()
{
GameObject[] enemies = GameObject.FindGameObjectsWithTag("Enemy");
float closestDist = range;
targetEnemy = null;
foreach (GameObject enemy in enemies)
{
float dist = Vector3.Distance(transform.position, enemy.transform.position);
if (dist < closestDist)
{
closestDist = dist;
targetEnemy = enemy.transform;
}
}
}
void RotateTowardsTarget()
{
Vector3 direction = targetEnemy.position - transform.position;
float angle = Mathf.Atan2(direction.y, direction.x) * Mathf.Rad2Deg;
Quaternion targetRotation = Quaternion.Euler(0, 0, angle);
transform.rotation = Quaternion.Lerp(transform.rotation, targetRotation,
Time.deltaTime * rotationSpeed);
}
}
Geometry Used: Distance formula, angle calculation, rotation, and Lerp for smooth turning.
Example 2: Platformer Ground Detection
A 2D platformer character needs to detect if they’re standing on solid ground.
public class PlayerController : MonoBehaviour
{
public float groundCheckDistance = 0.1f;
public LayerMask groundLayer;
private bool isGrounded;
void Update()
{
CheckGround();
}
void CheckGround()
{
// Cast a small circle beneath the player
Vector2 position = transform.position;
isGrounded = Physics2D.CircleCast(position, 0.5f, Vector2.down,
groundCheckDistance, groundLayer);
}
}
Geometry Used: Circle collision detection and distance measurement.
Example 3: Stealth Game Vision Cone
An enemy can only see the player if they’re within a certain angle and distance.
public class EnemyVision : MonoBehaviour
{
public float visionRange = 10f;
public float visionAngle = 90f;
public Transform player;
bool CanSeePlayer()
{
Vector3 toPlayer = player.position - transform.position;
float distance = toPlayer.magnitude;
// Check distance first (cheap operation)
if (distance > visionRange)
return false;
// Check angle (dot product)
Vector3 forward = transform.forward;
float dot = Vector3.Dot(forward, toPlayer.normalized);
float angle = Mathf.Acos(dot) * Mathf.Rad2Deg;
if (angle > visionAngle / 2f)
return false;
// Optional: Raycast to check for obstacles
RaycastHit hit;
if (Physics.Raycast(transform.position, toPlayer, out hit, distance))
{
return hit.transform == player;
}
return false;
}
}
Geometry Used: Distance formula, dot product for angle, and ray intersection.
Example 4: Racing Game Checkpoints
Detecting when a car passes through a checkpoint gate.
public class Checkpoint : MonoBehaviour
{
private Vector3 gateStart;
private Vector3 gateEnd;
private Vector3 lastCarPosition;
private bool carWasOnOtherSide = false;
void Start()
{
// Define gate endpoints
gateStart = transform.position - transform.right * 5f;
gateEnd = transform.position + transform.right * 5f;
}
void Update()
{
Vector3 carPosition = RaceManager.Instance.carPosition;
// Check which side of the line the car is on
float currentSide = WhichSide(gateStart, gateEnd, carPosition);
float lastSide = WhichSide(gateStart, gateEnd, lastCarPosition);
// If signs differ, the car crossed the line
if (Mathf.Sign(currentSide) != Mathf.Sign(lastSide))
{
OnCheckpointPassed();
}
lastCarPosition = carPosition;
}
float WhichSide(Vector3 lineStart, Vector3 lineEnd, Vector3 point)
{
Vector3 lineDir = lineEnd - lineStart;
Vector3 toPoint = point - lineStart;
return lineDir.x * toPoint.z - lineDir.z * toPoint.x;
}
}
Geometry Used: Cross product (2D version) to detect line crossing.
Common Geometry Mistakes in Game Development
Mistake 1: Using Expensive Operations in Loops
Bad:
foreach (Enemy enemy in enemies)
{
if (Vector3.Distance(player.position, enemy.position) < 10f)
{
// Attack
Good:
float rangeSq = 100f; // 10f squared
foreach (Enemy enemy in enemies)
{
Vector3 delta = player.position - enemy.position;
if (delta.sqrMagnitude < rangeSq)
{
// Attack
}
}
Why It Matters: Square root is 10-20x slower than multiplication. In a game with 1000 enemies, this saves thousands of CPU cycles per frame.
Mistake 2: Diagonal Movement Speed Bug
Bad:
void Update()
{
float speed = 5f;
transform.Translate(Input.GetAxis("Horizontal") * speed * Time.deltaTime, 0, Input.GetAxis("Vertical") * speed * Time.deltaTime);
}
Result: Diagonal movement is √2 (1.414x) faster—feels unfair and “slippery.”
Good: Normalize the input vector (Pythagorean theorem in action).
void Update()
{
float speed = 5f;
Vector3 input = new Vector3(Input.GetAxis("Horizontal"), 0, Input.GetAxis("Vertical"));
input = input.normalized * speed * Time.deltaTime;
transform.Translate(input);
}
Mistake 3: Frame-Rate Dependent Movement
Bad:
void Update()
{
transform.position += Vector3.forward * 5f * Input.GetKey("W"); // Jerky on high FPS
}
Good: Always multiply by Time.deltaTime.
void Update()
{
if (Input.GetKey("W"))
transform.position += Vector3.forward * 5f * Time.deltaTime;
}
Why It Matters: On a 60 FPS monitor, movement is smooth; on 1000 FPS, you’d teleport.
Mistake 4: Division by Zero in Slope/Angle Calculations
Bad:
float slope = (y2 - y1) / (x2 - x1); // Crash if x2 == x1 (vertical line)
Good: Use Mathf.Atan2(dy, dx)—handles all cases safely, including vertical/horizontal.
Mistake 5: Mixing Local and World Space
Bad:
// Assuming forward is always world Z
Vector3 forward = Vector3.forward;
Good:
Vector3 forward = transform.forward; // Object's local forward in world space
Why It Matters: Rotated objects break if you hardcode world axes.
Performance Optimization Tips for Geometry in Games
- Use Squared Distances: Skip
sqrt()90% of the time. - Built-in Functions:
Vector3.Distance(),Vector3.Dot(),Quaternion.LookRotation()are SIMD-optimized. - Spatial Partitioning: Quadtrees/Octrees for collision—reduces O(n²) checks to O(log n).
- Batch Operations: Use
Physics.OverlapSphere()or Unity’s Job System for parallel checks. - Fixed-Point Math: For retro/mobile games, avoid floats with integers (scale by 1000).
- LOD for Geometry: Simplify distant meshes; use fewer triangles.
| Optimization | Before (ms/frame) | After (ms/frame) | Improvement |
|---|---|---|---|
| Sqrt → Sq | 2.5 | 0.3 | 8x |
| Quadtree | 15.0 | 1.2 | 12x |
| Jobs/Burst | 10.0 | 0.8 | 12x |
Next Steps: Level Up Your Geometry Skills
- Practice: Build a simple physics sandbox in Unity—implement your own collision system.
- Engines: Unity/Godot/Unreal all expose these formulas via vectors/quaternions/matrices.
- Advanced Topics: Matrices for full transformations, ray-triangle intersection for picking, convex hulls for complex collision.
- Resources:
- “Game Programming Patterns” by Robert Nystrom (free online).
- Unity Learn: “Math for Game Developers.”
- Handmade Hero (Casey Muratori) for low-level math.
- 3Blue1Brown YouTube: Visual linear algebra.
Geometry isn’t just math—it’s the physics engine of your game. Master these formulas, and you’ll ship polished, performant games that feel incredible. Start coding today—what’s your first project?
Happy developing! 🚀



