Skip to content

Instantly share code, notes, and snippets.

@tinytengu
Created May 5, 2021 11:22
Show Gist options
  • Save tinytengu/4cae5623b0e898c30037f0e5c06d436d to your computer and use it in GitHub Desktop.
Save tinytengu/4cae5623b0e898c30037f0e5c06d436d to your computer and use it in GitHub Desktop.
Java 2D Vector Class Implementation
class Vector2D
{
public double vX;
public double vY;
public static int count = 0;
public Vector2D() {
this.vX = this.vY = 1.0;
count++;
}
public Vector2D(double x, double y)
{
this.vX = x;
this.vY = y;
count++;
}
public Vector2D(Vector2D source)
{
this.vX = source.vX;
this.vY = source.vY;
count++;
}
public void print()
{
System.out.printf("(%.2f, %.2f)\n", this.vX, this.vY);
}
public double length()
{
return Math.sqrt(Math.pow(this.vX, 2) + Math.pow(this.vY, 2));
}
public void add(Vector2D vector)
{
this.vX += vector.vX;
this.vY += vector.vY;
}
public void sub(Vector2D vector)
{
this.vX -= vector.vX;
this.vY -= vector.vY;
}
public void scale(double scaleFactor)
{
this.vX *= scaleFactor;
this.vY *= scaleFactor;
}
public void normalized()
{
double length = this.length();
this.vX /= length;
this.vY /= length;
}
public double dotProduct(Vector2D vector)
{
return this.vX * vector.vX + this.vY * vector.vY;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment