r/howdidtheycodeit • u/pmain8 • Apr 04 '22
Seeded 3D dice-rolling?
You could use a physics engine to simulate a die roll pretty easily by initializing the die with a random rotation and velocity, then waiting to see what face is up when it stops. However, what if you want to seed the random value of the die beforehand? Would you have to pre-record a simulation for each resulting die face and play back the appropriate animation, or is there a way to dynamically ensure the 3D die rolls believably and ends up on the corresponding face?
22
Upvotes
3
u/m0nkeybl1tz Apr 04 '22
Is there a purpose for this? What’s wrong with having 6 prerecorded animations?
3
u/Negative_Damage Apr 04 '22
To guarantee a dice roll output, if you want the physics to operate in real-time, with no texture swaps and no stored animation data, youre kinda limited in the same way as you would be in real life.
The simplest way i can think of is at the end of a genuine physics-based real-time roll, add a small force push until the desired number is on top.
The hardest way would be to tap into the physics engine code and generate the necessary prediction data, similar to how pool games work.
You could also weight the dice object itself, which should give you a biased outcome just like in real life. Not guaranteed by itself, but you would have to otherwise manipulate the roll less often.
The real answer is texture swap &/ stored animation if you want anything less than real-time in-engine.
2
u/nvec ProProgrammer Apr 10 '22
There may be a simpler way than this for you if you're just trying to prevent save-scumming.
When a physics engine is locked to a fixed step (50fps for example) then the rolls should be deterministic in that if the dice is thrown from the same orientation with the same force then it should always land in the position so will have the same number topmost. The fixed step removes any variety from framerate or other influences, it should be identical on a step-by-step basis every time it's run.
This means that all you need to do is save the number which is going to be used to initialise a random number generator for the random orientation at the start, and probably also used to adjust the initial force a little for variety, and you'll be able to guarantee every roll based on that seed will be identical.
Now the player saves their game and it saves the seed, rolls the dice and doesn't like the result, reloads and gets the same seed again, rerolls and gets the same result.
10
u/LtRandolphGames Apr 04 '22
In order to play back deterministically, the physics engine itself needs to be deterministic, which not all are. I'd recommend some googling to confirm that.
3
u/joonazan Apr 04 '22
Use the seed to randomize the dies starting orientation. However, if you do it with physics you have to very carefully make it deterministic to prevent cheating.
0
u/[deleted] Apr 04 '22
[deleted] — view deleted comment