Search code examples
javascriptmath3dformuladice

How to calculate the outcome of a simple dice in 3D space


So imagine you have a simple dice with 6 faces in 3D space. The dice has been made out of standard HTML elements and transformed into a 3D object. The starting position is always the same facing 1 upwards, 2 at the leftside and 3 toward the you (viewport).

Now you're able to rotate the dice using transform: rotateX, rotateY, rotateZ. For obvious reasons you're only able to rotate the dice by steps of 90deg each direction (negative aswell). Now what kind of formula do I have to use to calculate the final outcome.

Small example lets say: X = 3 (270deg), Y = 1 (90deg), Z = 2 (180deg) will result into throwing 3.

Do you see any logic involved into this because I dont seem to fully understand it.


Solution

  • Let's represent all those numbers as an object:

     const faces = { top: 1, left: 2, front: 3, bottom: 4, right: 5, back: 6 };
    

    Now if you rotate it to the right for example, you could swap the involved faces:

    const rotateToLeft = prev => ({
      top: prev.top,
      left: prev.front,
      front: prev.right,
      bottom: prev.bottom,
      right: prev.back,
      back: prev.left
    });
    

    Now you could do that with every direction, and then just rotate the dice as long as you need to get the result:

     let result = faces;
    
     for(let turn = 0; turn < 4 + Math.floor((X % 360) / 90); turn++)
       result = rotateToLeft(result);
    
     // repeat for y and z