Skip to content

Instantly share code, notes, and snippets.

@drahak
Created October 29, 2012 21:01
Show Gist options
  • Save drahak/3976518 to your computer and use it in GitHub Desktop.
Save drahak/3976518 to your computer and use it in GitHub Desktop.
Vector2 class
import 'dart:math';
/**
* Immutable Vector2 class
* @author Drahomír Hanák
*/
class Vector2
{
num _x;
num _y;
num get x => this._x;
num get y => this._y;
Vector2(num x, num y)
{
this._x = x;
this._y = y;
}
// Vector manipulation methods
Vector2 negate() => new Vector2(-this.x, -this.y);
Vector2 add(Vector2 vec) => new Vector2(this.x + vec.x, this.y + vec.y);
Vector2 sub(Vector2 vec) => new Vector2(this.x - vec.x, this.y - vec.y);
Vector2 mul(Vector2 vec) => new Vector2(this.x * vec.x, this.y * vec.y);
Vector2 div(Vector2 vec) => new Vector2(this.x / vec.x, this.y / vec.y);
Vector2 square() => new Vector2(this.x * this.x, this.y * this.y);
Vector2 abs() => new Vector2(this.x.abs(), this.y.abs());
num dot(Vector2 vec) => (this.x * vec.x) + (this.y * vec.y);
num length() => (this.x * this.x) + (this.y * vec.y);
num mod() => sqrt(this.length());
bool equals(Vector2 vec) => (this.x == vec.x) && (this.y == vec.y);
String toString() => '(' + this.x + ', ' + this.y + ')';
// Operators overloading
operator == (Vector2 vec) => this.equals(this, vec);
operator + (Vector2 vec) => this.add(this, vec);
operator - (Vector2 vec) => this.sub(this, vec);
operator * (Vector2 vec) => this.mul(this, vec);
operator / (Vector2 vec) => this.div(this, vec);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment