Math For Game Development

Concepts apply to all game making, not just Unity3D.


  • Direction to Position

Get direction Vector to the Player from current transform.

Normalizing means to scale the vector so that its length is 1. It is a useful operation in many computations, for example, normal vectors should be specified normalized for lighting calculations in computer graphics.

// get player direction
Vector3 playerDirection = (player.transform.position - transform.position).normalized;
  • Distance Between Vectors
// use Vector3.Distance
float distance = Vector3.Distance(transform.position, player.transform.position);

// or use magnitude
float distace2 = Vector3.Magnitude(transform.position - player.transform.position);
[Range(0.0f, 1.0f)]
public float weight = 0.5f; // 0 = completely 1st, 1 = completely 2nd

// newPosition is a combination of Vector3s position1 and position2 by weight
Vector3 newPosition = Vector3.Lerp(position1, position2, weight);
  • Get Angle
// get difference between positions
Vector3 delta = transform.position - target.transform.position;

// Would you look at it?
Quaternion look = Quaternion.LookRotation(delta);

// get angle on axis
// can use on other axes just use x or z in place of y
float horizontal = look.eulerAngles.y;

// might be off by 180 because of order of operation finding delta.
// adjust angle(off by 180), absolute value
float angle = Mathf.Abs((horizontal - 180) % 360);
  • Get Speed In A Direction
float fwdSpeed = Vector3.Dot(rigidbody.velocity, transform.forward);

Helpful Resources

  • Thanks to Asbjørn Thirslund - Game Math Theory - VECTORS

    Game Math Theory - VECTORS

  • Thanks to Jorge Rodriguez - Math for Game Developers - Distance Comparison

    Math for Game Developers - Distance Comparison