Skip to content

Commit b1a77e5

Browse files
the actual code stuff
0 parents  commit b1a77e5

File tree

2 files changed

+93
-0
lines changed

2 files changed

+93
-0
lines changed

collider.js

Lines changed: 74 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,74 @@
1+
class RectangleCollider {
2+
constructor(pos, size) {
3+
this.pos = pos;
4+
this.size = size;
5+
6+
// Restore everything to default settings
7+
this.clearLastCollisionFace();
8+
}
9+
10+
hitTopFace() {
11+
return this.hit && !this.horizontal && !this.left;
12+
}
13+
14+
hitUnderFace() {
15+
return this.hit && !this.horizontal && this.left;
16+
}
17+
18+
hitLeftFace() {
19+
return this.hit && this.horizontal && this.left;
20+
}
21+
22+
hitRightFace() {
23+
return this.hit && this.horizontal && !this.left;
24+
}
25+
26+
clearLastCollisionFace() {
27+
this.hit = false;
28+
this.horizontal = false;
29+
this.left = false;
30+
}
31+
32+
collideCalc(collider, collide) {
33+
this.clearLastCollisionFace();
34+
35+
// Return false if not colliding
36+
for (let i = 0; i < 2; i++)
37+
if (this.pos[i] >= collider.pos[i] + collider.size[i] ||
38+
collider.pos[i] >= this.pos[i] + this.size[i])
39+
return false;
40+
41+
this.hit = true;
42+
43+
// Generate centers
44+
let cents = [
45+
[undefined, undefined],
46+
[undefined, undefined]
47+
];
48+
49+
for (let i = 0; i < 2; i++) {
50+
cents[0][i] = this.pos[i] + (this.size[i] / 2);
51+
cents[1][i] = collider.pos[i] + (collider.size[i] / 2);
52+
}
53+
54+
let centDif = [undefined, undefined];
55+
for (let i = 0; i < 2; i++)
56+
centDif[i] = Math.abs(cents[0][i] - cents[1][i]);
57+
58+
this.horizontal = centDif[0] > centDif[1];
59+
const inHorizontal = Number(!this.horizontal);
60+
61+
this.left = cents[0][inHorizontal] < cents[1][inHorizontal];
62+
63+
if (collide)
64+
collider.pos[inHorizontal] =
65+
this.pos[inHorizontal] + (this.left ? this.size[1] : -collider.size[1]);
66+
67+
return true;
68+
}
69+
70+
p5DebugDraw() {
71+
rect(this.pos[0], this.pos[1],
72+
this.size[0], this.size[1]);
73+
}
74+
}

examples/sketch.js

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
function setup() {
2+
createCanvas(400, 400);
3+
}
4+
5+
let collider1 = new RectangleCollider([30, 20], [55, 55]);
6+
let collider2 = new RectangleCollider([25, 20], [32, 34]);
7+
8+
function draw() {
9+
background(51);
10+
collider1.p5DebugDraw();
11+
collider2.p5DebugDraw();
12+
collider1.collideCalc(collider2, true);
13+
console.log(`
14+
up: ${ collider1.hitTopFace() }
15+
down: ${ collider1.hitUnderFace() }
16+
left: ${ collider1.hitLeftFace() }
17+
right: ${ collider1.hitRightFace() }
18+
`);
19+
}

0 commit comments

Comments
 (0)