Skip to content

Instantly share code, notes, and snippets.

@beProsto
Created May 3, 2020 01:00
Show Gist options
  • Save beProsto/4620cb6b1b3139ef0b06f8ef4c9c8d7b to your computer and use it in GitHub Desktop.
Save beProsto/4620cb6b1b3139ef0b06f8ef4c9c8d7b to your computer and use it in GitHub Desktop.
It comes out that i can't find pastehub anywhere :D
class Collider {
constructor() {
this.base = [{x: -0.15, y: -0.15}, {x: 0.0, y: 0.15}, {x: 0.15, y: -0.15}];
this.col = [{x: -0.15, y: -0.15}, {x: 0.0, y: 0.15}, {x: 0.15, y: -0.15}];
this.pos = {x: 0.0, y: 0.0};
this.inter = false;
}
update() {
for(let i = 0; i < this.base.length; i++) {
this.col[i] = {x: this.base[i].x + this.pos.x, y: this.base[i].y + this.pos.y};
}
}
setModel(model) {
for(let i = 0; i < model.length / 2; i++) {
this.base[i] = {x: model[i * 2], y: model[i * 2 + 1]};
}
}
collides(other) {
let c1 = this;
let c2 = other;
this.inter = true;
for(let i = 0; i < 2; i++) {
if(i == 1) {
c1 = other;
c2 = this;
}
for(let a = 0; a < c1.col.length; a++) {
const b = (a + 1) % c1.col.length;
let axisProj = {x: -(c1.col[b].y - c1.col[a].y), y: c1.col[b].x - c1.col[a].x};
const dist = Math.sqrt(axisProj.x * axisProj.x + axisProj.y * axisProj.y);
axisProj.x = axisProj.x / dist;
axisProj.y = axisProj.y / dist;
let minR1 = Infinity;
let maxR1 = -Infinity;
for(let p = 0; p < c1.col.length; p++) {
const q = (c1.col[p].x * axisProj.x + c1.col[p].y * axisProj.y);
minR1 = Math.min(minR1, q);
maxR1 = Math.max(maxR1, q);
}
let minR2 = Infinity;
let maxR2 = -Infinity;
for(let p = 0; p < c2.col.length; p++) {
const q = (c2.col[p].x * axisProj.x + c2.col[p].y * axisProj.y);
minR2 = Math.min(minR2, q);
maxR2 = Math.max(maxR2, q);
}
if(!(maxR2 >= minR1 && maxR1 >= minR2)) {
this.inter = false;
return false;
}
}
}
return true;
}
draw(vb, sh) {
sh.set2f("u_Offset", this.pos.x, this.pos.y);
if(this.inter) {
sh.set4f("u_Color", 0.0, 0.0, 1.0, 1.0);
}
else {
sh.set4f("u_Color", 1.0, 0.0, 0.0, 1.0);
}
vb.draw();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment