4
\$\begingroup\$

I am trying to convert this velocity into another 2 dimensional vector at some specified angle:

float maximumVelocity = 1.5f;
float angleInDegrees = 23f;
Vector2 actualVelocityAs2DimensionalVector = {?,?}

At first, I was going to take 1.5, and rotate it after converting the degrees to radians, like so:

double radians = Math.toRadians(angleInDegrees);
Vector2 actualVelocityAs2DimensionalVector = new Vector2(x * Math.cos(radians) - y * Math.sin(radians), 
                                                         x * Math.sin(radians) + y * Math.cos(radians));

Is this the fastest way to achieve this? This will be happening a lot in my application, and I would think all the cos and sin calls are somewhat expensive.

\$\endgroup\$
6
\$\begingroup\$

You're calling Math.sin() and Math.cos() twice as many times as you need to.

double cosine = Math.cos(radians)
double sine = Math.sin(radians)
Vector2 rotated = new Vector2(x*cosine - y*sine, x*sine + y*cosine)

If the angle never changes, then just save the values cosine and sine so you don't have to compute them over and over again.

\$\endgroup\$
1
\$\begingroup\$

Lookup table

The way you are doing it is correct other than what @user5402 said about duplicate calls.

If this is a time critical part of your application and you need it to be faster, you could use a lookup table instead. The drawback is that you will have limited accuracy. For example, if your angle is limited to one degree increments, you could build a table of sin values of size [360]. Then instead of calling Math.sin() and Math.cos(), you could just look up the answers in your table (cosine can be looked up in the same table if you just add 90 degrees).

If you need more accuracy, such as to 0.1 degree, you could make your table bigger. At some accuracy level though, the table size becomes impractical and you should just use the functions.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.