Vectors and Limitting Velocity

Wondering what your guys’ thoughts on this might be:
So I have space ship flying around. I might write some code like this:

float acceleration;
Vector2 velocity;
Vector2 position;
//…
//…
velocity.add(acceleration);
position.add(velocity);

What would you propose I should do if I wanted to limit the maximum velocity? Currently, as you can see, velocity would add up to infinity since it keeps adding acceleration.

Maybe you might think I would write something like this?

velocity.add(acceleration);
if(velocity.getMagnitude() > maximumAllowableVelocity){
Vector2.normalize(velocity);
velocity.multiply(maximumAllowableVelocity();
}
position.add(velocity);

But even that does not get me what I am looking for. If you have been in a similar situation, do you remember what you did to resolve this issue? Thanks in advance.

So, but I think I already found the solution. What I mentioned above actually WILL work- as long as you are consistent with your data types. I was mixing between floats and doubles. When I converted everything to a float, the issue seemed to be fixed. Sorry to waste your time :slight_smile:

I’m only posting this because back when I was studying physics I designed a space simulator (planets, binary solar systems, satellites, gravity etc.). While doing so I learned something really helpful that I never knew about previous to designing that sim. I’m not sure how accurate you need your program to be, but if you’re working with floats and doubles you may run into some accuracy errors while trying to use Java’s standard math operators (E.g. >, <, ==, >=, <=). You should write a few methods using an Epsilon to compensate for Java’s inherent inaccuracy when it comes to floats/float math.

Ex. here’s one method I wrote up:


public static final double EPSILON = 0.00001;

public static boolean areEqual(float f0, float f1)
{
	return f0 == f1 || Math.abs(f0 - f1) < EPSILON;
}

Basically floats are inherently inaccurate due to Java’s floating point arithmetic and how the variable is stored, so you need to compensate for that with your maths. I know this isn’t entirely related to your original post, but it does still apply because it could possibly cause issues for something like limiting the speed accurately. Not trying to be an annoyance, just recommending you look into it. :slight_smile:

Umm…

Just my two cents (sense it). When you want to limit something between A and B, you should use Math.max(a, b) where a is the testing value returned if a < b. if a >= b then it returns b.

I am sure you can ignore the epsilon in this case, given you don’t need to be 100% accurate.