This repository has been archived on 2022-11-26. You can view files and clone it, but cannot push or open issues or pull requests.
dwelibs/src/controller.js

64 lines
1.6 KiB
JavaScript

DWE.Controller = {}
DWE.Controller.Entity = class Entity extends DWE.Math.Box2 {
constructor (x, y, w, h) {
super(x, y, w, h)
this.velocity = new DWE.Math.Vector2(0, 0)
this.scale = 1
}
collide (map, collisionLayer, mapOrigin, viewport) {
let dir = map.collideLayer(this, mapOrigin, viewport, collisionLayer, 2 * this.scale * map.tileWidth)
if (dir === 'l' || dir === 'r') {
this.velocity.x = 0
} else if (dir === 'b' && this.velocity.y < 0) {
this.velocity.y = 0
} else if (dir === 't' && this.velocity.y > 0) {
this.velocity.y = 0
}
}
update (delta) {
this.x += this.velocity.x * delta
this.y += this.velocity.y * delta
}
}
// A platformer entity
DWE.Controller.OrthoEntity = class OrthoEntity extends DWE.Controller.Entity {
constructor(x, y, w, h) {
super(x, y, w, h)
this.grounded = false
this.jumping = false
}
collide (map, collisionLayer, mapOrigin, viewport) {
let collision = map.collideLayer(this, mapOrigin, viewport, collisionLayer, 2 * this.scale * map.tileWidth)
this.grounded = false
if (collision) {
if (collision.dir === 'l' || collision.dir === 'r') {
this.velocity.x = 0
this.jumping = false
} else if (collision.dir === 'b') {
this.grounded = true
this.jumping = false
} else if (collision.dir === 't') {
this.velocity.y *= -1
this.jumping = false
}
this.x -= collision.x
this.y -= collision.y
}
}
update (delta) {
if (this.grounded)
this.velocity.y = 0
this.x += this.velocity.x * delta
this.y += this.velocity.y * delta
}
}