Created
August 22, 2022 05:55
-
-
Save brecert/695e0988b81c01fcb5a2a22622fa771b to your computer and use it in GitHub Desktop.
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 COLLIDABLE = document.getElementsByClassName('collidable') | |
const Direction = { | |
None: 0, | |
Left: -1, | |
Right: 1 | |
} | |
const State = { | |
Walking: 0, | |
Falling: 1, | |
Climbing: 2, | |
Squashed: 3, | |
Angel: 4, | |
Idle: 5, | |
} | |
class Entity { | |
state = State.Falling | |
dir = Direction.None | |
constructor(x = 0, y = 0) { | |
this.x = x | |
this.y = y | |
const $el = document.createElement('div') | |
$el.classList.add('entity') | |
this.el = $el | |
document.body.append($el) | |
} | |
updateCollisions() { | |
this.collidable = new WeakSet(COLLIDABLE) | |
} | |
collisionAt(x, y) { | |
const els = document.elementsFromPoint(x, y) | |
for(const el of els) { | |
if (this.collidable.has(el)) { | |
return el | |
} | |
} | |
} | |
isSquished() { | |
let isInside = this.collisionAt(this.x, this.y) | |
if (isInside) { | |
let isSquished = [1, -1].every(x => | |
[1, -1].every(y => | |
this.collisionAt(this.x + x, this.y + x) | |
) | |
) | |
return isSquished | |
} | |
return false | |
} | |
next() { | |
this.updateCollisions() | |
if (this.isSquished()) { | |
this.state = State.Squashed | |
} | |
if (this.state === State.Walking || this.state == State.Falling) { | |
let groundCollision = this.collisionAt(this.x, this.y + 1) | |
if (!groundCollision) { | |
this.y += 1 | |
this.dir = Direction.None | |
} | |
let wallCollision = this.collisionAt(this.x + (1 * this.dir), this.y) | |
if (wallCollision) { | |
this.dir = this.dir * -1 | |
} | |
if (groundCollision && this.dir === Direction.None) { | |
this.dir = Direction.Right | |
} | |
this.x = this.x + (1 * this.dir) | |
} | |
if (this.state == State.Squashed) { | |
console.log('Squashed') | |
} | |
this.render() | |
} | |
render() { | |
this.el.style.top = `${this.y}px` | |
this.el.style.left = `${this.x}px` | |
} | |
collide(el) { | |
const { top, left, right } = el.getBoundingClientRect() | |
// const wallCollision = this.dir === Direction.Right ? (this.x + 1) >= left : (this.x - 1) < right | |
const wallCollision = this.dir === Direction.Right && (this.x - left) < 0 | |
if (wallCollision) { | |
this.dir = this.dir * -1 | |
} | |
} | |
} | |
const entity = new Entity(20, 0) | |
const onFrame = (timestamp) => { | |
entity.next() | |
requestAnimationFrame(onFrame) | |
} | |
onFrame() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment