Seeded Dice Roller

Rolling a die in 3D is simple enough, but what if you want to choose the result beforehand? How do you seed the roll to make it land on a specific number? The answer is forward-simulated physics and a lot of vector math!

This tool was implemented in Unity with C#. All pictured assets were made by me using Maya and Photoshop.

Coming soon to the Unity asset store! In the meantime, try it yourself here.

Process

Choose face to roll

Simulate roll physics

Rotate simulated die to chosen face

Use rotation of simulated die as offset for original die

After a desired face is chosen, a duplicate die is made. The physics of the initial velocity and torque values that will be used for the die roll are simulated on duplicate until it would become still. During each simulated step, the transform values of the duplicate are recorded for later use. Once the simulation is finished, if the duplicate die is not already showing the chosen face, it is rotated to show that face in the same orientation as the roll result. This rotation is the amount that the original die must also be rotated from its starting orientation in order to end up rolling the desired result.


Once all this is calculated, the recorded simulation steps, with the rotational offset, are applied to the original die one frame at a time. This gives the appearance that the die is being physically rolled to produce the predefined result.

Shape-agnostic

The same algorithm is used to calculate the rotational offset for each of these shapes. In fact, any polyhedron can be used as long as the orientations of the die before and after adding the rotational offset are isomorphic (i.e. the same physical space is occupied, only the rotation of the object changes). This is accomplished by using the relative positions and orientations of the rolled and desired faces to calculate the rotational axes and amounts necessary to alter the orientation.

Custom faces and meshes

The representation of the die is also written in such a way as to be agnostic of what each face represents; all the die knows is what face has been rolled, it's up to the handler consuming the result to decide what that result means. This makes it easy to create custom dice, allowing the user to map any data type of their choice to each face with whatever code is interpreting the roll result.

And of course, the mesh can look like whatever you want, as long as the collider used in the physics simulation and the layout of the faces follow the isomorphism rule.