hakubaa
hakubaa

Reputation: 315

Rotate object and then translate it

I have an object (i.e. rectangle) described by three variables: x (int), y (int) - position of the object and rangel (float) - angel indicating of the object's direction movement. Now I would like to translate the object in accordacne with it's direction (angel). I figured out how to calculate its new coordinates:

x += (int)(shift*Math.sin(Math.toRadians(rangel));
y -= (int)(shift*Math.cos(Math.toRadians(rangel));

but I'm not sure if this method is effective enough. Do you now any other way to perform this operation, but that will work faster than presented above? Thanks.

Upvotes: 0

Views: 156

Answers (3)

samjaf
samjaf

Reputation: 1053

According to this thread Math.sin does not necessarily use an optimal implementation. Since you already cast to int, I would strongly suggest using some approximation instead of Math.sin. I found this post which seems to provide a both accurate and fast algorithm for approximating sin(x). I'm pretty sure you'll find an approximation for cos(x) or can derive it on your own from the given solution.

Furthermore I suppose there are even faster approximations for the special case of neglecting decimal precision.

Best regards, sam

Upvotes: 1

Dawood ibn Kareem
Dawood ibn Kareem

Reputation: 79818

It might be slightly faster to calculate Math.toRadians(rangel) first and store it in a local variable, so you only have to calculate it once, not twice. But the savings from this would be tiny. Other than that, this looks pretty optimal to me.

Note, though, that if there were only a small number of different possible values for rangel (for example, you can only move the object in 24 different directions, or something like that), then you'd get some savings by using a look-up table for the sin and cos values.

Upvotes: 0

alex
alex

Reputation: 490173

That is the correct way to translate an object by an angle. If angle is arbitrary, then there is no faster way.

Upvotes: 0

Related Questions