How to Store Vectors in Java? What's the Data Type?
I just read this tutorial. It's about game development, and it basically says that I need to store acceleration, velocity, posit开发者_如何学运维ion as vectors to make game physics. Hope it makes sense! I need to choose data type now... for example I need to store values like...
(3, 5, 2)
(6, 2, 3)
(2, 3)
Also, I will need to do addition and subtraction like this...
(0, 1, 4) + (3, -2, 5) = (0 + 3, 1 - 2, 4 + 5) = (3, -1,9)
What data type should I use in this situation?
For one vector two integers (floats/doubles) maybe? Maybe array for one vector where where values are integers (floats/doubles)?
Sounds like you want three values (probably doubles):
public class Vector3
{
private final double x;
private final double y;
private final double z;
public Vector3(double x, double y, double z)
{
this.x = x;
this.y = y;
this.z = z;
}
public Vector3 plus(Vector3 other)
{
return new Vector3(x + other.x, y + other.y, z + other.z);
}
// etc
}
Note that I've made this immutable - which isn't always the best choice for performance (which may be relevant in your situation) but helps with readability.
Perhaps commons-math OpenMapRealVector
can be of use.
Or you can use generics:
public interface MathVector<T extends Number>
{
MathVector<T> add(MathVector<T> addend);
T innerProduct();
// Vectors have more than this, but it makes the point
}
精彩评论