How to do this coordinate system operation more efficiently?

泄露秘密 提交于 2020-01-15 16:00:22

问题


I'm making a 3D game, where the player's back should always be facing the camera and he should move in that direction. I didn't come to the "back facing the camera" part yet, but I believe that it will be simple once I figure out how to move the player in the right direction...

Though it is a 3D coordinate system, height can be ignored (z-axis) because no matter how high the camera is, the player should always be going in the same speed (the camera system is planned to function much like in the game World of Warcraft).

Now, I have summarized my problem to this...

  • Point (0, 0) is the players position.
  • Point (x, y) is the camera's position.
  • The camera is (dx, dy) units away from the player (and because player is at (0, 0), it is also (x, y) units away, although this is a position vector, not a translation one)

Problem: how do I get a point (a, b) in this 2D space that lies on a circle r = 1 but is on the same line as (0, 0) and (x, y)?

Visualization:

By doing this, I should have a 2D vector (a, b), which would, when multiplied by -30, act as the speed for the player.

I know how to do this, but in a very expensive and inefficient way, using the Pythagora's theorem, square roots, and all those out-of-the-question tools (working in Javascript).

Basically, something like this:

c = sqrt(dx*dx + dy*dy); //Get the length of the line
rat = 1/c; //How many times is the desired length (1) bigger than the actual length

a = x*rat;
b = y*rat;

There must be something better!

For reference, I'm making the game in Javascript, using the Three.js engine.


回答1:


There is nothing to make more efficient here, these calculations are standard stuff for 3D scenes.

Don't optimize prematurely. There is no way this stuff is a bottleneck in your app.

Remember, even if these calculations happen on each render(), they still only happen once every several milliseconds - 17ms assuming 60 FPS, which is a lot. Math.sin() / Math.cos() / Math.sqrt() are plenty efficient, and lots of other calculations happen on each render() that are much more complex.

You'll be just fine with what you have now.



来源:https://stackoverflow.com/questions/10773693/how-to-do-this-coordinate-system-operation-more-efficiently

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!