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)
Intersection of 2 secant lines
- line 1: y = a * x + b
- line 2: y' = a' * x + b'
- intersection point P:
- xP = (a - a')/(b' - b);
- yP = a * xP + b;
- Ex with y = 5*x+1 & y' = 2*x+8:
- xP = 7/3;
- yP = 12.666;
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 and the origin
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)
- It's the same as applying the following rotation matrix:
vec2 (
+cos(a), -sin(a)
+sin(a), +cos(a)
)
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)
- http://www.cse.yorku.ca/~amana/research/grid.pdf
- http://en.wikipedia.org/wiki/Bresenham%27s_line_algorithm
- Demo by xem: http://codepen.io/xem/pen/RRxPNG?editors=1010
Projection of a plane on a sphere (on a 2D canvas)
- new_y = Math.sin(-y * Math.PI/2);
- new_x = Math.sin(x * Math.PI) * Math.cos(y * Math.PI / 2);
- if Math.abs(x) < .5, the projected point is hidden "behind" the sphere.
- Prototype by subzey: http://codepen.io/subzey/pen/rVoXQx
- Demo by xem: http://xem.github.io/articles/demos/js13k15/globe2.html
2D jumps / gravity (ex: for side-view platform games)
- let x, y the position of the object (ex: 0, 0)
- let vx, vy the horizontal and vertical speed of the object (ex: 0, 0)
- let g, the gravity (which is a downwards acceleration, ex: -10)
- during the frame at the start of the jump: set vy to a high value, ex: 50
- during all the frames of the jump:
- Add g to vy (ex: 40, 30, 20, 10, 0, -10, ...)
- Add vy to y (ex: 40, 70, 90, 100, 100, 90, ...)
- place the object at [x,y]
Also applicable to all kind of accelerations in x or y directions.
Distance between a point and a line
- line: a *x + b * y + c = 0
- point: xA, yA
- distance: d = Math.abs(a * xA + b * yA + c) / Math.sqrt(a * a + b * b)