98 lines
2.4 KiB
JavaScript
98 lines
2.4 KiB
JavaScript
|
DWE.Math = {}
|
||
|
|
||
|
DWE.Math.random = function (i,j) {
|
||
|
return Math.floor(Math.random() * j) + i
|
||
|
}
|
||
|
|
||
|
DWE.Math.lerp = function (v0, v1, t) {
|
||
|
return (1 - t) * v0 + t * v1
|
||
|
}
|
||
|
|
||
|
DWE.Math.reverseLerp = function (v0, v1, t) {
|
||
|
return 1.0 / ((v1 - v0) * t)
|
||
|
}
|
||
|
|
||
|
DWE.Math.intersectsBox = function (ax, ay, aw, ah, bx, by, bw, bh) {
|
||
|
return (Math.abs(ax - bx) * 2 <= (aw + bw)) &&
|
||
|
(Math.abs(ay - by) * 2 <= (ah + bh))
|
||
|
}
|
||
|
|
||
|
DWE.Math.intersects2Box = function (a, b) {
|
||
|
return (Math.abs(a.x - b.x) * 2 <= (a.width + b.width)) &&
|
||
|
(Math.abs(a.y - b.y) * 2 <= (a.height + b.height))
|
||
|
}
|
||
|
|
||
|
DWE.Math.clamp = function (val, min, max) {
|
||
|
return Math.max(min, Math.min(max, val))
|
||
|
}
|
||
|
|
||
|
// Two-dimensional vector
|
||
|
|
||
|
DWE.Math.Vector2 = class {
|
||
|
constructor (x, y) {
|
||
|
this.x = x
|
||
|
this.y = y
|
||
|
}
|
||
|
|
||
|
get magnitude () {
|
||
|
return Math.abs(Math.sqrt((this.x * this.x) + (this.y * this.y)))
|
||
|
}
|
||
|
|
||
|
normalize () {
|
||
|
var len = this.magnitude
|
||
|
this.x /= len
|
||
|
this.y /= len
|
||
|
}
|
||
|
|
||
|
distance (vec) {
|
||
|
if (!(vec instanceof DWE.Math.Vector2)) throw new Error('Distance function takes another Vector2 as an argument.')
|
||
|
return Math.abs(Math.sqrt(Math.pow(vec.x - this.x, 2) + Math.pow(vec.y - this.y, 2)))
|
||
|
}
|
||
|
}
|
||
|
|
||
|
// A box.
|
||
|
|
||
|
DWE.Math.Box2 = class {
|
||
|
constructor (x, y, w, h) {
|
||
|
this.x = x
|
||
|
this.y = y
|
||
|
this.width = w
|
||
|
this.height = h
|
||
|
}
|
||
|
|
||
|
intersectsBox (box) {
|
||
|
if (!(box instanceof DWE.Math.Box2)) throw new Error('Intersection function takes another Box2 as an argument.')
|
||
|
return DWE.Math.intersects2Box(this, box)
|
||
|
}
|
||
|
|
||
|
intersectsCircle (circle) {
|
||
|
if (!(circle instanceof DWE.Math.Circle)) throw new Error('Intersection function takes another Circle as an argument.')
|
||
|
var circleDistance = new DWE.Math.Vector2(Math.abs(circle.x - this.x), Math.abs(circle.y - this.y))
|
||
|
|
||
|
if (circleDistance.x > (this.width/2 + circle.r)) return false
|
||
|
if (circleDistance.y > (this.height/2 + circle.r)) return false
|
||
|
|
||
|
if (circleDistance.x <= (this.width/2)) return true
|
||
|
if (circleDistance.y <= (this.height/2)) return true
|
||
|
|
||
|
var cornerDistance_sq = Math.pow(circleDistance.x - this.width/2, 2) +
|
||
|
Math.pow(circleDistance.y - this.height/2, 2)
|
||
|
|
||
|
return (cornerDistance_sq <= Math.pow(circle.r, 2))
|
||
|
}
|
||
|
}
|
||
|
|
||
|
// A circle.
|
||
|
|
||
|
DWE.Math.Circle = class {
|
||
|
constructor (x, y, r) {
|
||
|
this.x = x
|
||
|
this.y = y
|
||
|
this.r = r
|
||
|
}
|
||
|
|
||
|
get radius () {
|
||
|
return this.r
|
||
|
}
|
||
|
}
|