In the process of developing my 3D game, I have encountered a scenario where the player's back needs to always face the camera while moving in that direction. Although I haven't quite figured out how to achieve the "back facing the camera" aspect yet, I am confident that it will be straightforward once I crack how to move the player correctly...
Despite working within a 3D coordinate system, I can safely disregard height (z-axis) since regardless of the camera's elevation, the player's movement speed must remain consistent (my camera system is designed to function akin to World of Warcraft).
I have distilled my issue down to this essence...
- The player's position is at point (0, 0).
- The camera is positioned at point (x, y).
- The distance between the player and the camera is represented by the vector (dx, dy) units away (given that the player is located at (0, 0), this is effectively (x, y) units away, although specified as a position vector rather than a translational one).
Question: How do I determine a point (a, b) within this 2D space that lies on a circle with radius r = 1, aligning with the same line as (0, 0) and (x, y)?
Visualization:
This calculation should result in a 2D vector (a, b) which, when multiplied by -30, would dictate the player's speed.
While I have a method to accomplish this task using Pythagoras's theorem, square roots, and other less-than-ideal tools (operating in Javascript), it proves costly and inefficient.
Essentially, something like this:
c = sqrt(dx*dx + dy*dy); // Calculate the length of the line
rat = 1/c; // Determine how many times the desired length (1) surpasses the actual length
a = x*rat;
b = y*rat;
There has to be a more efficient approach!
By way of context, I am crafting the game in Javascript utilizing the Three.js engine.