{"id":13446169,"url":"https://github.com/terkelg/math","last_synced_at":"2025-05-12T15:32:26.701Z","repository":{"id":66028063,"uuid":"48323844","full_name":"terkelg/math","owner":"terkelg","description":"Math snippets with graphic programming in mind.","archived":false,"fork":false,"pushed_at":"2016-11-17T02:42:26.000Z","size":10,"stargazers_count":117,"open_issues_count":0,"forks_count":12,"subscribers_count":6,"default_branch":"master","last_synced_at":"2025-04-01T07:53:18.702Z","etag":null,"topics":["math","math-snippets","spring","velocity"],"latest_commit_sha":null,"homepage":"","language":null,"has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/terkelg.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":null,"code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null}},"created_at":"2015-12-20T14:23:31.000Z","updated_at":"2024-10-15T07:52:55.000Z","dependencies_parsed_at":null,"dependency_job_id":"f3f3ba62-b49a-4d52-b3f9-4e64ff8e032f","html_url":"https://github.com/terkelg/math","commit_stats":null,"previous_names":[],"tags_count":0,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/terkelg%2Fmath","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/terkelg%2Fmath/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/terkelg%2Fmath/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/terkelg%2Fmath/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/terkelg","download_url":"https://codeload.github.com/terkelg/math/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":253766002,"owners_count":21960832,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["math","math-snippets","spring","velocity"],"created_at":"2024-07-31T05:00:47.553Z","updated_at":"2025-05-12T15:32:26.447Z","avatar_url":"https://github.com/terkelg.png","language":null,"funding_links":[],"categories":["[Other](https://github.com/lrunaways/awesome-deep-learning-mustreads/blob/master/topics/Other.rst)","Math"],"sub_categories":["Other"],"readme":"# Math Snippets\n\u003e Math snippets with graphic programming in mind.\n\nThis is work in progress.\n**To-do:**\n- [ ] Convert all snippets to JS (Some are Action Script)\n- [ ] Add live code examples\n- [ ] Add simple desciptions\n\n## Contents\n - [Snippets](https://github.com/terkelg/math/blob/master/README.md#snippets)\n\t- [Radias \u0026 Degrees](https://github.com/terkelg/math#radians--degrees)\n\t- [Calculate side lengths](https://github.com/terkelg/math#calculate-side-lengths)\n\t- [Rotate a 2D point](https://github.com/terkelg/math#rotate-a-2d-point)\n\t- [Linear distance bwetween 2 points](https://github.com/terkelg/math#linear-distance-2-points)\n\t- [Linear distance between 2 vectors](https://github.com/terkelg/math#linear-distance-between-2-vectors)\n\t- [Length of a vector (Magnitude)](https://github.com/terkelg/math#length-of-a-vector)\n\t- [Add and substract vectors](https://github.com/terkelg/math#add-and-substract-vectors)\n\t- [Normalize vector](https://github.com/terkelg/math#normalize-vector)\n\t- [Dot product vectors](https://github.com/terkelg/math#dot-product-vectors)\n\t- [Finding angle between 2 points](https://github.com/terkelg/math#finding-angle-between-2-points)\n\t- [Finding angle between 2 vectors](https://github.com/terkelg/math#finding-angle-between-2-vectors)\n\t- [Cross Product](https://github.com/terkelg/math#cross-product)\n\t- [Rotate to the mouse (or any point)](https://github.com/terkelg/math#rotate-to-the-mouse-or-any-point)\n\t- [Create waves](https://github.com/terkelg/math#create-waves)\n\t- [Hex to decimal](https://github.com/terkelg/math#hex-to-decimal)\n\t- [Decimal to hex](https://github.com/terkelg/math#decimal-to-hex)\n\t- [Combine component colors](https://github.com/terkelg/math#combine-component-colors)\n\t- [Extract component colors](https://github.com/terkelg/math#extract-component-colors)\n\t- [Draw a curve through a point](https://github.com/terkelg/math#draw-a-curve-through-a-point)\n\t- [Convert angular velocity to x, y velocity](https://github.com/terkelg/math#convert-angular-velocity-to-x-y-velocity)\n\t- [Convert angular acceleration or any other force to x and y](https://github.com/terkelg/math#convert-angular-acceleration-or-any-other-force-to-x-and-y)\n\t- [Add acceleration to velocity](https://github.com/terkelg/math#add-acceleration-to-velocity)\n\t- [Add velocity to position](https://github.com/terkelg/math#add-velocity-to-position)\n\t- [Testing for out of bound](https://github.com/terkelg/math#testing-for-out-of-bound)\n\t- [Apply friction (correct way)](https://github.com/terkelg/math#apply-friction-correct-way)\n\t- [Apply friction (the easy way)](https://github.com/terkelg/math#apply-friction-the-easy-way)\n\t- [Simple easing, long form](https://github.com/terkelg/math#simple-easing-long-form)\n\t- [Simple easing, abbreviated form](https://github.com/terkelg/math#simple-easing-abbreviated-form)\n\t- [Simple easing, short form](https://github.com/terkelg/math#simple-easing-short-form)\n\t- [Simple spring, long form](https://github.com/terkelg/math#simple-spring-long-form)\n\t- [Simple spring, abbreviated form](https://github.com/terkelg/math#simple-spring-abbreviated-form)\n\t- [Simple spring, short form](https://github.com/terkelg/math#simple-spring-short-form)\n\t- [Offset spring](https://github.com/terkelg/math#offset-spring)\n\t- [Distance-based collision detection](https://github.com/terkelg/math#distance-based-collision-detection)\n\t- [Multiple-objects collision detection](https://github.com/terkelg/math#multiple-objects-collision-detection)\n\t- [Coordinate rotation](https://github.com/terkelg/math#coordinate-rotation)\n\t- [Reverse coordiante rotation](https://github.com/terkelg/math#reverse-coordiante-rotation)\n\t- [Conservation of momentum in ActionScript (with a shortcut)](https://github.com/terkelg/math#conservation-of-momentum-in-actionscript-with-a-shortcut)\n\t- [Gravity implementation](https://github.com/terkelg/math#gravity-implementation)\n - [Resources](https://github.com/terkelg/math#resources)\n\n\n## Snippets\n\n### Radians \u0026 Degrees\n\n```\nradians = degrees * Math.PI / 180;\ndegrees = radians * 180 / Math.PI;\n```\n\n```js\n// JavaScript\nvar angleInDegrees = 45;\nvar radians = angleInDegrees * Math.PI / 180;\nvar backToDegrees = radians * 180 / Math.PI;\n```\n\n### Calculate side lengths\n#### SOHCAHTOA\n\n###### Calculate basic trigonometric functions\n```\nSine of an angle = opposite / hypotenuse\nCosine of an angle = adjacent / hypotenuse\nTangent of angle = opposite / adjacent\n```\n\n```js\n// Javascript\nvar hyp = 100;\nvar angleDegrees = 45;\nvar angleRadians = angleDegrees * Math.PI / 180;\n\nvar opposite = Math.sin( angleRadians ) * hyp;\nvar adjacent = Math.cos( angleRadians ) * hyp;\nvar tangent  = opposite / adjacent;\n```\n\n### Rotate a 2D point\n```js\nvar vec2 = {x: 2, y: 3};\nvar rotatedVector = rotate2D(vec2, angle);\n\nfunction rotate2D(vector, angle)\n{\n\tvar theta = angle * Math.PI / 180; // radians\n\tvar matrix = [  Math.cos(theta),  Math.sin(theta), \n\t\t\t\t\t-Math.sin(theta), Math.cos(theta)\n\t\t\t\t\t];\n\t\t\t\t\t\n\treturn { \n\t\tx: matrix[0] * vector.x + matrix[1] * vector.y, \n\t\ty: matrix[2] * vector.x + matrix[3] * vector.y\n\t};\n}\n\n```\n\n### Linear distance between 2 points\n```\ndx = x2 - x1;\ndy = y2 - y1;\ndist = Math.sqrt(dx*dx + dy*dy);\n```\n\n```js\n// JavaScript\nvar x1 = 3;\nvar x2 = 5;\nvar distance = x2 — x1;\n```\n\n### Linear distance between 2 vectors\n#### a² + b² = c²\n\n```js\n// Javascript\nvar v1 = {x: 4, y: -9};\nvar v2 = {x: 5, y: 15};\n\nvar distance = Math.sqrt( Math.pow((v2.x — v1.x), 2) + Math.pow((v2.y — v1.y), 2) );\n```\n\n### Length of a vector\n#### Magnitude \n\n```js\n// Javascript\n// 2D -\u003e hypotenuse\nvar v = {x: 4, y:-9};\nvar length = Math.sqrt( (Math.pow(v.x, 2) + Math.pow(v.y, 2)) );\n\n// 3D\nvar v = {x: 4, y:-9, z: 0.5};\nvar length = Math.sqrt( (Math.pow(v.x, 2) + Math.pow(v.y, 2) + Math.pow(v.z, 2) ));\n```\n\n### Add and substract vectors\n\n```js\nvar v1 = {x: 2, y: 3};\nvar v2 = {x: 2, y: -2};\nvar addedVec = {x: v1.x + v2.x, y: v1.y + v2.y};\nvar subVec = {x: v1.x - v2.x, y: v1.y - v2.y};\n```\n\n### Normalize vector\n\n```js\n// Javascript\n// 2D\nvar v = {x: 4, y:-9};\nvar length = Math.sqrt( (Math.pow(v.x, 2) + Math.pow(v.y,2)) );\nvar n = {x: v.x / length, y: v.y / length};\n\n// 3D\nvar v = {x: 4, y:-9, z: 3};\nvar length = Math.sqrt( Math.pow(v.x, 2) + Math.pow(v.y,2) + Math.pow(v.z,2) );\nvar n = {x: v.x / length, y: v.y / length, z: v.z / length};\n```\n\n### Dot product vectors\n\n```js\n// Javascript\nvar v1 = {x: 4, y: 5, z: 9};\nvar v2 = {x: 5, y: 9, z: -5};\nvar dot = (v1.x * v2.x) + (v1.y * v2.y) + (v1.z * v2.z);\n```\n\n### Finding angle between 2 points\n\n```js\n//Javascript\nvar x = -3;\nvar y = -2;\nvar radians = Math.atan2(x, y);\nvar degrees = radians * 180 / Math.PI;\n```\n\n### Finding angle between 2 vectors\n\n```js\n// Javascript\nvar v1 = {x: 4, y: 5, z: 9};\nvar v2 = {x: 5, y: 9, z: -5};\nvar dot = (v1.x * v2.x) + (v1.y * v2.y) + (v1.z * v2.z);\n\nvar lengthv1 = length(v1); // see length\nvar lengthv2 = length(v2); // see length\n\nvar radians = Math.acos(dot / (lengthv1 * lengthv2));\nvar angle = radians * 180 / Math.PI;\n```\n\n### Cross Product\n\n```js\n// Javascript\nvar v1 = {x: 1, y: 2, z: 3};\nvar v2 = {x: 3, y: 2, z: 1};\nvar cross = {\n\tx: v1.y*v2.z - v1.z*v2.y, \n\ty: v1.z*v2.x - v1.x*v2.z, \n\tz: v1.x*v2.y - v1.y*v2.x\n};\n```\n\n### Rotate to the mouse (or any point)\n```js\nvar dx = mouseX - spriteX;\nvar dy = mouseY - spriteY;\nsprite.rotation = Math.atan2(dy, dx) * 180 / Math.PI;\n```\n\n### Create waves\n```js\n// value can be properties like x, y, alpha, rotation etc.\npublic function onEnterFrame(event:Event) {\n  value = center + Math.sin(angle) * range;\n  angle += speed;\n}\n```\n\n### Hex to decimal\n```\ntrace(hexValue);\n```\n\n### Decimal to hex\n```\ntrace(decimalValue.toString(16));\n```\n\n### Combine component colors\n```\ncolor24 = red \u003c\u003c 16 | green \u003c\u003c 8 | blue;\ncolor32 = alpha \u003c\u003c 24 | red \u003c\u003c 16 | green \u003c\u003c 8 | blue;\n```\n\n### Extract component colors\n```\nred = color24 \u003e\u003e 16;\ngreen = color24 \u003e\u003e 8 \u0026 0xFF;\nblue = color24 \u0026 0xFF;\n\nalpha = color32 \u003e\u003e 24;\nred = color24 \u003e\u003e 16 \u0026 0xFF;\ngreen = color24 \u003e\u003e 8 \u0026 0xFF;\nblue = color24 \u0026 0xFF;\n```\n\n### Draw a curve through a point\n```\n//xt, yt is the point to draw through\n// x0, y0, x2, y2 is the end points\nx1 = xt * 2 - (x0 - x2) / 2;\ny1 = yt * 2 - (y0 - y2) / 2;\nmoveTo(x0, y0);\ncurveTo(x1, y1, x2, y2);\n```\n\n### Convert angular velocity to x, y velocity\n```\nvx = Math.cos(angle) * speed;\nvy = Math.sin(angle) * speed;\n```\n\n### Convert angular acceleration or any other force to x and y\n```\nax = Math.cos(angle) * force;\nay = Math.sin(angle) * force;\n```\n\n### Add acceleration to velocity\n```\nvx += ax;\nvy += ay;\n```\n\n### Add velocity to position\n```\nsprite.x += vx;\nsprite.y += vy;\n```\n\n### Testing for out of bound\n```\nif(sprite.x - sprite.width / 2 \u003e right) ||\n  sprite.x - sprite.width / 2 \u003c left ||\n  sprite.y - sprite.height / 2 \u003e bottom ||\n  sprite.y - sprite.height / 2 \u003c top)\n{\n  //remove or reposition sprite\n}\n```\n\n### Apply friction (correct way)\n```\nspeed = Math.sqrt(vx*vx + vy*vy);\nangle = Math.atan2(vy, vx);\nif(speed \u003e friction)\n{\n  speed -= friction;\n} else {\n  speed = 0;\n}\nvx = Math.cos(angle) * speed;\nvy = Math.sin(angle) * speed;\n```\n\n### Apply friction (the easy way)\n```\nvx *= friction;\nvy *= friction;\n```\n\n### Simple easing, long form\n```\nvar dx = targetX - sprite.x;\nvar dy = targetY - sprite.y;\nvx = dx * easing;\nvy = dy * easing;\nsprite.x += vx;\nsprite.y += vy;\n```\n\n### Simple easing, abbreviated form\n```\nvx = (targetX - sprite.x) * easing;\nvy = (targetY - sprite.y) * easing;\nsprite.x += vx;\nsprite.y += vy;\n```\n\n### Simple easing, short form\n```\nsprite.x += (targetX - sprite.x) * easing;\nsprite.y += (targetY - sprite.y) * easing;\n```\n\n### Simple spring, long form\n```\nvar ax = (targetX - sprite.x) * spring;\nvar ay = (targetY - sprite.y) * spring;\nvx += ax;\nvy += ay;\nvx *= friction;\nvy *= friction;\nsprite.x += vx;\nsprite.y += vy;\n```\n\n### Simple spring, abbreviated form\n```\nvx = (targetX - sprite.x) * spring;\nvy = (targetY - sprite.y) * spring;\nvx *= friction;\nvy *= friction;\nsprite.x += vx;\nsprite.y += vy;\n```\n\n### Simple spring, short form\n```\nvx = (targetX - sprite.x) * spring;\nvy = (targetY - sprite.y) * spring;\nsprite.x += (vx *= friction);\nsprite.y += (vy *= friction);\n```\n\n### Offset spring\n```\nvar dx = sprite.x - fixedX;\nvar dy = sprite.y - fixedY;\nvar angle = Math.atan2(dy, dx);\nvar targetX = fixedX + Math.cos(angle) * springLength;\nvar targetY = fixedY + Math.sin(angle) * springLength;\n// Spring to targetX and targetY;\n```\n\n### Distance-based collision detection\n```\n// Starting with spriteA and spriteB\n// If using a plain sprite, or obejct without a radius property\n// you can use with and height divided by 2\n\nvar dx = spriteB.x - spriteA.x;\nvar dy = spriteB.y - spriteA.y;\nvar dist = Math.sqrt(dx*dx + dy*dy);\nif(dist \u003c spriteA.radius + spriteB.radius)\n{\n  // handle collision\n}\n```\n\n### Multiple-objects collision detection\n```\nvar numObjects = 10;\nfor (var i = 0; i \u003c numObjects; i++)\n{\n  var objectA = objects[i];\n  for (var j = i+1; j \u003c numObjects; j++)\n  {\n    var objectB = objects[j];\n    // perform collision detection\n    // between objectA and objectB\n  }\n}\n```\n\n### Coordinate rotation\n```\nx1 = Math.cos(angle) * x - Math.sin(angle) * y;\ny1 = Math.cos(angle) * y + Math.sin(angle) * x;\n```\n\n### Reverse coordiante rotation\n```\nx1 = Math.cos(angle) * x + Math.sin(angle) * y;\ny1 = Math.cos(angle) * y - Math.sin(angle) * x;\n```\n\n### Conservation of momentum in ActionScript (with a shortcut)\n```js\nvar vxTotal = vx0 - vx1;\nvx0 = ((ball0.mass - ball1.mass) * vx0 + 2 * ball1.mass * vx1) / (ball0.mass + ball1.mass);\nvx1 = vxTotal + vx0;\n```\n\n### Gravity implementation\n```js\nfunction gravitate(partA, partB) {\n  var dx = partB.x - partA.x;\n  var dy = partB.y - partA.y;\n  var distSQ  = dx*dx + dy*dy;\n  var dist = Math.sqrt(distSQ);\n  var force = partA.mass * partB.mass / distSQ;\n  var ax = force * dx / dist;\n  var ay = force * dy / dist;\n  partA.vx += ax / partA.mass;\n  partA.vy += ay / partA.mass;\n  partB.vx += ax / partB.mass;\n  partB.vy += ay / partB.mass;\n}\n```\n\n\n# Resources\n- [Coding Math](https://www.youtube.com/channel/UCF6F8LdCSWlRwQm_hfA2bcQ) ([Github](https://github.com/bit101/codingmath))\n- [Generative Art by Matt Pearson](https://www.manning.com/books/generative-art)\n- [Math as code](https://github.com/Jam3/math-as-code)\n- [BetterExplained.com](http://betterexplained.com/)\n- [Essence of linear algebra](https://www.youtube.com/watch?v=kjBOesZCoqc)\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fterkelg%2Fmath","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fterkelg%2Fmath","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fterkelg%2Fmath/lists"}