I have 3rd party tool on our website that displays 3D models. I have to built a cube
that can control the camera of this 3D viewer.
Something like this:
This cube should rotate based on the camera of the viewer. The camera has following functions:
camera.getPosition()
camera.getDirection()
camera.getUp()
and returned values look like this:
camera.getPosition: {"x":-0.14815343916416168,"y":0.10964569449424744,"z":0.0968131348490715}
camera.getDirection: {"x":0.7116152048110962,"y":-0.5266535878181458,"z":-0.46501585841178894}
camera.getUp: {"x":0.38310256600379944,"y":0.8456945419311523,"z":-0.3715282082557678}
How can I calculate the rotation of my cube using these values? (If possible)
My solution ended up being this:
// http://www.fundza.com/vectors/normalize/index.html
const normalize = ({ x, y, z }) => {
const length = Math.sqrt(x * x + y * y + z * z)
return {
x: x / length,
y: y / length,
z: z / length
}
}
// https://mathjs.org/docs/reference/functions/cross.html
const cross = ({ x: a1, y: a2, z: a3 }, { x: b1, y: b2, z: b3 }) => ({
x: a2 * b3 - a3 * b2,
y: a3 * b1 - a1 * b3,
z: a1 * b2 - a2 * b1
})
const calculateRotation = (direction, up) => {
const right = normalize(cross(direction, up))
const matrix = [[right.x, right.y, right.z], [direction.x, direction.y, direction.z], [up.x, up.y, up.z]]
const angle = Math.acos((matrix[0][0] + matrix[1][1] + matrix[2][2] - 1) * 0.5)
const axis = (() => {
const k = Math.sqrt(
Math.pow(matrix[2][1] - matrix[1][2], 2) +
Math.pow(matrix[0][2] - matrix[2][0], 2) +
Math.pow(matrix[1][0] - matrix[0][1], 2)
)
return {
x: (matrix[2][1] - matrix[1][2]) / k,
y: (matrix[0][2] - matrix[2][0]) / k,
z: (matrix[1][0] - matrix[0][1]) / k
}
})()
return { angle, axis }
}
Then you can rotate with:
cubeGroup.setRotationFromAxisAngle(rotation.axis, rotation.angle)
And I also had to rotate my camera, which might be optional for other cases:
camera.rotateX(Math.PI / 2)