Skip to content

Instantly share code, notes, and snippets.

@Dormilich
Last active November 13, 2020 15:20
Show Gist options
  • Save Dormilich/2580b76084edd94c1be00aa9e39aa791 to your computer and use it in GitHub Desktop.
Save Dormilich/2580b76084edd94c1be00aa9e39aa791 to your computer and use it in GitHub Desktop.
Follow the movement of an object
/**
* Create an immutable vector object. There's no assumption made on what
* the "unit" and hence the meaning of the vector is.
*
* @param (Number) x - vector value in x-direction
* @param (Number) y - vector value in y-direction
* @return (Object)
*/
function vector(x, y)
{
var obj = Object.create(vector.prototype)
Object.defineProperty(obj, 'x', { value: +x.toFixed(vector.scale) })
Object.defineProperty(obj, 'y', { value: +y.toFixed(vector.scale) })
return obj
}
// account for floating-point math inaccuracy
vector.scale = 6
// define how x/y change over time
vector.prototype.delta = false
// calculate the next trajectory point
vector.prototype.next = function (time=0) {
if (!this.delta) {
return this
}
var delta = this.delta.next(time)
var obj = this.add(delta.mult(time))
obj.delta = delta
return obj
}
// vector math - addition
vector.prototype.add = function (vec) {
return vector(this.x + vec.x, this.y + vec.y)
}
// vector math - multiplication
vector.prototype.mult = function (factor) {
return vector(this.x * factor, this.y * factor)
}
// vector math - vector length
vector.prototype.valueOf = function () {
return +Math.sqrt(this.x * this.x + this.y * this.y).toFixed(vector.scale)
}
// textual representation
vector.prototype.toString = function () {
return `(${this.x}, ${this.y})`
}
/**
* Example: the trajectory of a moving object under the influence of gravity
*/
// object position
var obj = vector(10, 10)
// object speed
var speed = vector(10, 5)
// object acceleration
var gravity = vector(0, -9.81)
// the object's position is changed by its current speed
obj.delta = speed
// the object's speed is altered by the gravity
speed.delta = gravity
while (obj.y >= 0) {
// work well only if the interval is sufficiently small => cf. differential calculus
obj = obj.next(0.001)
console.log(obj.x, obj.y)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment