I'm experiencing a bit of weirdness. I have a cube on the page, that can be rotated in 2 ways:
- if the user mouses around near an edge of the cube, it will "tip" in that direction, exposing the hidden side of the cube.
- If the cube is currently "tipped" and the exposed side of the cube is clicked, the cube will rotate so that this side is facing the user.
// on mouse enter, "tip" the cube to expose the nearest hidden face
$(".overlay").mouseenter(function () {
var direction = $(this).attr("class").split(" ")[0];
var tease = getTease(direction);
$("#cube").css({ transform: 'translateZ(-100px) ' + tease });
$(".overlay").toggleClass("teasing");
// on mouse leave, reset the cube
}).mouseleave(function () {
$("#cube").css({ transform: 'translateZ(-100px) rotateX(' + rotateX + 'deg) rotateY(' + rotateY + 'deg)' });
$(".overlay").toggleClass("teasing");
});
// if the user clicks the exposed side of a cube, rotate that side to face them
$(document).on("click", ".overlay.teasing", function () {
var direction = $(this).attr("class").split(" ")[0];
var rotate = getRotate(direction);
$("#cube").css({ transform: 'translateZ(-100px) ' + rotate });
});
If you rotate to the left or right, everything works fine. If you rotate the cube around the X axis (rotating it away or towards the user), then suddenly the "tipping" is broken on the left and right sides. I imagine that this is a problem with my understanding. At first I thought the answer was that, when the cube is rotated around the X axis, the Y axis itself rotates to point towards the user. This would explain why the cube now tips in the wrong direction: it is tipping around a Y axis that is directed at the user. However, on further experimenting I noticed that this behaviour is not consistent between the X and Y axis. That is to say, spinning the cube left/right and then up/down works fine. Spinning the cube up/down and then left/right is broken.
Does anyone understand why?
Here is a working fiddle of my little experiment (tested in webkit and gecko). Apologies for the mess: I've tried to comment it as well as possible, because it just represents me messing around for a couple of hours and isn't the prettiest code.
note: I notice this question has been asked in one way or another a number of times on SO, but I haven't found a satisfying answers. This question in particular is full of useful information and tutorials. I'm sure I could implement the solution that uses matrixes. What I'm interested in, in my particular case, is why the cube works fine with left/right then up/down, but not the other way.