Created
July 11, 2020 18:15
-
-
Save EduardoJM/e357517d992d59a8286479714321ba45 to your computer and use it in GitHub Desktop.
Separating Axis Theorem Testing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const canvas = document.getElementById('game'); | |
const context = canvas.getContext('2d'); | |
const polygons = []; | |
const polygonsColors = [ 'red', 'blue', 'green', 'pink', 'purple', 'cyan' ]; | |
polygons.push(createPolygon([ | |
{ x: 50, y: 50 }, | |
{ x: 100, y: 50 }, | |
{ x: 100, y: 150 }, | |
{ x: 50, y: 150 }, | |
])); | |
polygons.push(createPolygon([ | |
{ x: 75 + 100, y: 50 + 25 }, | |
{ x: 100 + 100, y: 150 + 25 }, | |
{ x: 50 + 100, y: 150 + 25 }, | |
])); | |
function testCollision() { | |
for (let i = 1; i < polygons.length; i++) { | |
if (polygons[0].testWith(polygons[i])) { | |
console.log("Tested with index: ", i); | |
} | |
} | |
} | |
document.addEventListener('keydown', function(e) { | |
if (e.key === 'ArrowRight') { | |
polygons[0].offset(10, 0); | |
testCollision(); | |
render(); | |
} else if (e.key === 'ArrowLeft') { | |
polygons[0].offset(-10, 0); | |
testCollision(); | |
render(); | |
} else if (e.key === 'ArrowDown') { | |
polygons[0].offset(0, 10); | |
testCollision(); | |
render(); | |
} else if (e.key === 'ArrowUp') { | |
polygons[0].offset(0, -10); | |
testCollision(); | |
render(); | |
} | |
}); | |
function render() { | |
context.fillStyle = 'black'; | |
context.fillRect(0, 0, canvas.width, canvas.height); | |
let colorIndex = 0; | |
for (let i = 0; i < polygons.length; i++) { | |
polygons[i].render(context, polygonsColors[colorIndex]); | |
colorIndex++; | |
if (colorIndex === polygonsColors.length) { | |
colorIndex = 0; | |
} | |
} | |
} | |
render(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment