Skip to content

Instantly share code, notes, and snippets.

@jamesmoriarty
Created April 2, 2012 10:23
Show Gist options
  • Save jamesmoriarty/2282401 to your computer and use it in GitHub Desktop.
Save jamesmoriarty/2282401 to your computer and use it in GitHub Desktop.
Vector2
class Vector2
# A 2 coordinate vector.
# http://en.wikipedia.org/wiki/Coordinate_vector
# @param x The x coordinate of the vector
# @param y The y coordinate of the vector
constructor:(@x = 0, @y = 0) ->
# Add 2 vectors.
# @param vector A vector
# @return vector
add:(vector) -> new Vector2(@x + vector.x, @y + vector.y)
# Substract 2 vectors.
# @param vector A vector
# @return vector
sub:(vector) -> new Vector2(@x - vector.x, @y - vector.y)
# Scale this vector.
# @param vector A vector
# @return vector
scale:(factor) -> new Vector2(@x * factor, @y * factor)
# Calculate the length of this vector.
# @param void
# @return vector
length:() -> Math.sqrt(@x * @x + @y * @y)
# Get the normalized vector.
# @param void
# @return vector
normalize:() -> new Vector2(@x / @.length(), @y / @.length())
# Get 2 vectors dot product.
# @param vector A vector
# @return The dot product
dot:(vector) -> @x * vector.x + @y * vector.y
# Get the perpendicular vector.
# http://en.wikipedia.org/wiki/Perpendicular_vector
# @param void
# @return vector
perp:() -> new Vector2(-@y, @x)
window.Vector2 = Vector2
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment