I'm currently developing a 3D game and I am facing a challenge with ensuring that the player mesh is always oriented towards the back of the camera. Although I have successfully obtained a 2D speed vector representing the direction along the x-z plane, I am now stuck on how to correctly rotate the mesh based on this speed vector...
Each mesh in my game has a property called .rotation
, which holds a 3D vector. My main focus is on rotating the mesh around the y-axis, as it is perpendicular to the x-z plane.
Since the rotation is measured in radians instead of degrees, I attempted an equation like this:
mesh.rotation.y = (mesh.direction.x - mesh.direction.z) * Math.PI * 2;
However, this approach doesn't seem to be achieving the desired effect...
The direction/speed consists of a 2D vector containing real numbers ranging from -1 to 1. The magnitude of the vector remains constant, denoted by sqrt(x*x + y*y) == 1
, forming a "circle" pattern to maintain equal speed in all directions.
The speed vector updates whenever the mouse drags over the screen, causing the rotation to adjust accordingly. The calculation for updating the speed vector looks like this:
var c = Math.sqrt(cameraPos.x*cameraPos.x + cameraPos.z*cameraPos.z); // This represents the distance from the camera to the mesh location, assumed to be at (0, 0) for simplicity.
var rat = 1 / c;
mesh.direction.x = cameraPos.x * rat; // Direction vector equals the speed vector
mesh.direction.z = cameraPos.z * rat;