Approach 2D position
I started working on a concept that requires me to find a way to move a rectangle toward a given point at a given speed. I'm developing for Android so this is relatively speed critical (it's going to be calculated every frame for potentially hundreds of objects, as well.)
The solutions I could think of are as follows:
float diff_x = x2 - x1;
float diff_y = y2 - y1;
float length = sqrt((diff_x * diff_x) + (diff_y * diff_y));
float dir_x = diff_x / len;
float dir_y = diff_y / len;
float move_x = dir_x * MOVE_SPEED;
float move_y = dir_y * MOVE_SPEED;
As you can see, this way requires a square root, which I know to be quite costly. I thought of an alternative, which uses trigonometry, but it's costly as well.
float diff_x = x2 - x1;
float diff_y = y2 - y1;
float angle = atan2(diff_y, diff_x);
float move_x = sin(angle) * MOVE_SPEED;
float move_y = cos(angle) * MOVE_SPEED;
Are there any other way开发者_开发百科s? If not, which of my solutions would be faster? Thanks for any help.
A very common tric you can use is to put everything squarred/power of two/ ^2
this way instead of using sqrt you just use
length = (diff_x * diff_x) + (diff_y * diff_y);
diff_x*diff_x/length
精彩评论