Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@tomhodgins
Forked from xem/readme.md
Created July 14, 2016 13:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tomhodgins/3f55dbf5843c126d35ac8d8032e0e5b5 to your computer and use it in GitHub Desktop.
Save tomhodgins/3f55dbf5843c126d35ac8d8032e0e5b5 to your computer and use it in GitHub Desktop.
Maths & trigonometry cheat sheet for 2D games

Conventions

  • o = [xo = 0, yo = 0] is the origin
  • A = [xA, yA] is a point on the 2D plane. Same for B, C, ...
  • lengths are in any unit (ex: pixels)
  • code snippets are in JavaScript

Degrees to radians

angleRad = angleDeg * Math.PI / 180;

Radians to degrees

angleDeg = angleRad * 180 / Math.PI;

Distance between two points (Pythagore)

  • dist = function(A,B){ return Math.sqrt((xB - xA)*(xB - xA) + (yB - yA)*(yB - yA)) } // ES5
  • dist = (A, B) => Math.hypot(xB -xA, yB -yA) // ES6

Line passing through 2 points

  • line equation: y = ax + b
  • a = (yB - yA) / (yB - yA) = tan θ
  • θ = angle between line and x axis
  • b = yA - a * xA (because yA = a * xA + b)

Angle in radians between the x axis at the origin and a point on the plane

angle = Math.atan2(Ax, Ay)

Angle in radians between two points

angle = Math.atan2(By - Ay, Bx - Ax);

Rotate a point (angle in radians)

  • Anew_x = Ax * Math.cos(angle) - Ay * Math.sin(angle)
  • Anew_y = Ax * Math.sin(angle) + Ay * Math.cos(angle)

Project a point on the trigonometric circle

  • Anew_x = Math.cos(atan2(Ax, Ay))
  • Anew_y = Math.sin(atan2(Ax, Ay))

Intersections between a line and the grid (2D raycasting)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment