I need a (simple), immutable, 2D vector library for Java or Scala
I've been searching for a whole day. I've tried Simplex3D Scala library. But it's poorly documented and I开发者_如何学Python don't even manage to get a vector normalized after downloading an older release because the current one doesn't run.
javax.vecmath is not immutable so it not nice to use in Scala.
commons-math is more into the scientific math direction with no convenience for 2D (or 3D) use.
I couldn't find one when I needed one. So I built one, and I've always been intending to release it. I'm too busy to do anything with it now, but I could probably make it available next week if a better answer is not forthcoming.
I've just done some more research. Slick2D seems to contain a Vector2f class that has immutable methods. Though that's not very much and can be done by hand in maybe an hour.
Here's the one I made for some simple game stuff.
It hardly perfect and it's not entirely immutable. I wanted non-immutable versions of the operators for some pieces of code. Originally it wrapped the Vector2 class of JBox2D as well, which lacked operator overloads and a bunch of other stuff.
package Ostkaka
import scala.math
/**
* Date: 2010-okt-06
*/
class Vector2(private var _x: Float, private var _y: Float) {
def x = _x
def y = _y
def +(v: Vector2) = {var c = Vector2(x, y); c += v; c}
def +=(v: Vector2) = {
this._x += v.x
this._y += v.y
()
}
def -(v: Vector2) = {var c = Vector2(x, y); c -= v; v}
def -=(v: Vector2) = {
this._x -= v.x
this._y -= v.y
()
}
def /(factor: Float) = {var c = Vector2(x, y); c /= factor; c}
def /=(factor: Float) = {
this *= (1 / factor);
()
}
def *(factor: Float) = {var c = Vector2(x, y); c *= factor; c}
def *=(factor: Float) = {
this._x *= factor
this._y *= factor
()
}
def unary_- : Vector2 = Vector2(-x, -y)
def magnitude = (math.sqrt (x * x + y * y).toDouble).toFloat
def normalised = this / magnitude
def dot(v: Vector2) = x * v.x + y * v.y
def project(v: Vector2) = {
val axis = v.normalised
axis * (this dot axis)
}
}
object Vector2
{
def zero = new Vector2(0, 0)
def unitX = new Vector2(1, 0)
def unitY = new Vector2(0, 1)
implicit def Tuple2FloatToVector2(v: (Float, Float)): Vector2 = {
new Vector2(v._1, v._2)
}
def apply(): Vector2 = {
new Vector2(0, 0)
}
def apply(x: Float, y: Float): Vector2 = {
new Vector2(x, y)
}
}
Simplex3d Math follows GLSL very closely, so any manual on GLSL will work as well.
You can normalize vector 'v' as follows: normalize(v)
Simplex3d Math is a library and does not come with runnable classes, so I am not sure what you mean by "the new release does not run." Please join the mailing list and give more details, I'll be more than happy to assist you there: http://groups.google.com/group/simplex3d-dev
Documentation will be improved for the next release.
精彩评论