Skip to content

Instantly share code, notes, and snippets.

@nicklanng
Created January 6, 2015 10:10
Show Gist options
  • Save nicklanng/f1406e5181803b442817 to your computer and use it in GitHub Desktop.
Save nicklanng/f1406e5181803b442817 to your computer and use it in GitHub Desktop.
CoffeeScript Example
class Vector3
add: (additional) ->
new Vector3 @x + additional.x,
@y + additional.y,
@z + additional.z
subtract: (subtrahend) ->
new Vector3 @x - subtrahend.x,
@y - subtrahend.y,
@z - subtrahend.z
divideScalar: (scalar) ->
new Vector3 @x / scalar,
@y / scalar,
@z / scalar
multiplyScalar: (scalar) ->
new Vector3 @x * scalar,
@y * scalar,
@z * scalar
magnitude: ->
Math.pow Math.pow(@x, 2) + Math.pow(@y, 2) + Math.pow(@z, 2), 0.5
normalize: ->
this if magnitude == 0
@divideScalar @magnitude
module.exports = Vector3
function Vector3(x, y, z) {
this.x = x
this.y = y
this.z = z
}
Vector3.prototype.add = function(additional) {
return new Vector3(this.x + additional.x, this.y + additional.y, this.z + additional.z)
}
Vector3.prototype.subtract = function(subtrahend) {
return new Vector3(this.x - subtrahend.x, this.y - subtrahend.y, this.z - subtrahend.z)
}
Vector3.prototype.divideScalar = function(scalar) {
return new Vector3(this.x / scalar, this.y / scalar, this.z / scalar)
}
Vector3.prototype.multiplyScalar = function(scalar) {
return new Vector3(this.x * scalar, this.y * scalar, this.z * scalar)
}
Vector3.prototype.magnitude = function() {
return Math.pow(Math.pow(this.x, 2) + Math.pow(this.y, 2) + Math.pow(this.z, 2), 0.5)
}
Vector3.prototype.normalize = function() {
var magnitude = this.magnitude();
if (magnitude == 0) {
return this
}
return this.divideScalar(this.magnitude())
}
module.exports = Vector3
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment