https://gyazo.com/bf02862401fdc3ce21c02f60402c8b3b
Disclaimer: This asset contains highly abstract programmer art, You’ve Been Warned!
I decided to make this random feature and Open Sourced it because I thought it would be fun and a nice opportunity for the community to learn from it
So what does it do?
- Rolls the Dice with physics when a button is pressed
- Waits for the Dice to stop moving
- Delivers the Result in the Output
“Well that’s pretty simple, isn’t it?”
You can take a look at GetTop
function by @Corecii then decide if it’s simple or not; I’m sure that you can learn a lot from that which it contains pretty advance CFrame and Vector math.
Either way I took the approach to make the Dice’s results determined by physics rather than a RNG before the Roll, to add a little uniqueness to the Asset.
Resources
Feel free to use this asset in anyway you desire, there’s nothing stopping you!
Roll The Dice!.rbxl (25.2 KB)
–
Code
local Dice = workspace.Box.Dice
local Button = script.Parent
local Debounce
local function GetTop() -- Credit to @Corecii
-- world-space up direction to compare again
local upVec = Vector3.new(0, 1, 0)
-- vars to find maximum
local maxDotValue, maxDotNormalId
-- loop through all possible faces
for _, normalId in ipairs(Enum.NormalId:GetEnumItems()) do
-- get object-space direction for this face
local vec = Vector3.FromNormalId(normalId)
-- get world-space direction for this face
local diceVecInWorldSpace = workspace.Box.Dice.CFrame:VectorToWorldSpace(vec)
-- Dot gets cos(angle) between upVec and diceVecInWorldSpace
-- acos(dot) is a value between 1 (same direction) and -1 (opposite directions)
-- common values you need to know here:
-- 1: same direction entirely
-- bigger than 0: same side
-- 0: perpendicular directions
-- smaller than 0: opposite sides
-- -1: opposite direction entirely
local dotValue = upVec:Dot(diceVecInWorldSpace)
if not maxDotValue or dotValue > maxDotValue then
maxDotValue, maxDotNormalId = dotValue, normalId
end
end
return maxDotNormalId.Name
end
local valuesLookup = {
Back = 4,
Bottom = 6,
Front = 3,
Left = 2,
Right = 5,
Top = 1
}
Button.MouseButton1Down:Connect(function()
if not Debounce then
Debounce = true
Dice.RotVelocity = Vector3.new(math.random(-10,10)*50,math.random(-10,10)*50,math.random(-10,10)*50)
Button.TextColor3 = Color3.new(1,0,0)
repeat wait(.5) until Dice.Velocity == Vector3.new(0,0,0)
local top = GetTop()
print(top, valuesLookup[top])
Button.TextColor3 = Color3.new(0,1,0)
Debounce = false
end
end)
Enjoy!