Cookbook
Short recipes for jobs most games need, each in Gama and then Luau. They're written to paste into a project's main.gma or main.luau and run as they are.
- A main menu
- Saving settings
- A countdown timer
- A health bar
- A door that slides open
- Clicking on parts
- Walking a path
- Key bindings
A main menu
A full-window menu with a title and two buttons. Play removes the menu and starts the game; Quit closes it.
fn startGame()
print("the game starts here")
end
let menu: Surface
menu = Surface {
Target = "Window",
AlignItems = "Center",
JustifyContent = "Center",
Gap = 12,
Background = $10131a,
Widgets.Theme(),
Text { Text = "Robot Yard", FontSize = 48, FontWeight = 700, Color = $ffffff },
Widgets.Button({ Text = "Play", Width = 200, Activated = fn()
menu:Destroy()
startGame()
end }),
Widgets.Button({ Text = "Quit", Width = 200, Variant = "ghost", Activated = fn()
Process:Exit()
end }),
Parent = Scene,
}local function startGame()
print("the game starts here")
end
local menu
menu = Ui.Surface({
Target = Enum.SurfaceTarget.Window,
AlignItems = Enum.Align.Center,
JustifyContent = Enum.Justify.Center,
Gap = 12,
Background = Color.fromHex("#10131a"),
Widgets.Theme(),
Ui.Text({ Text = "Robot Yard", FontSize = 48, FontWeight = 700, Color = Color.new(1, 1, 1) }),
Widgets.Button({
Text = "Play",
Width = 200,
Activated = function()
menu:Destroy()
startGame()
end,
}),
Widgets.Button({
Text = "Quit",
Width = 200,
Variant = "ghost",
Activated = function()
Process:Exit()
end,
}),
})
menu.Parent = SceneThe buttons take Enter and Space once focused, and Tab moves between them. See Widgets.
Saving settings
A volume slider whose value outlives the game. Data stores save to the player's machine under Gamma play; the state keeps the slider, the sound and the saved value in step.
let settings = DataStores:GetDataStore("Settings")
let volume = Ui.State(settings:GetAsync("Volume") ?? 50)
let music = Sound { SoundId = "assets/Theme.ogg", Looped = true, Parent = Scene }
on volume.Changed(value)
music.Volume = value / 100
settings:SetAsync("Volume", value)
end
music.Volume = volume:Get() / 100
Surface {
Target = "Window",
Padding = 20,
Gap = 8,
Widgets.Theme(),
Text { Text = "Music volume" },
Widgets.Slider({ Value = volume, Min = 0, Max = 100, Step = 5, Width = 240 }),
Parent = Scene,
}local settings = DataStores:GetDataStore("Settings")
local volume = Ui.State(settings:GetAsync("Volume") or 50)
local music = Instance.new("Sound")
music.SoundId = "assets/Theme.ogg"
music.Looped = true
music.Parent = Scene
volume.Changed:Connect(function(value)
music.Volume = value / 100
settings:SetAsync("Volume", value)
end)
music.Volume = volume:Get() / 100
Ui.Surface({
Target = Enum.SurfaceTarget.Window,
Padding = 20,
Gap = 8,
Widgets.Theme(),
Ui.Text({ Text = "Music volume" }),
Widgets.Slider({ Value = volume, Min = 0, Max = 100, Step = 5, Width = 240 }),
}).Parent = SceneSave a table under one key to keep several settings together: settings:SetAsync("Video", { Shadows = true, Scale = 1 }).
A countdown timer
Counts down from a minute on screen and says when time is up.
let left = 60
let label = Text { Text = "1:00", FontSize = 32, Color = $ffffff }
Surface { Target = "Window", Padding = 20, label, Parent = Scene }
every 1 do
left -= 1
label.Text = string.format("%d:%02d", left // 60, left % 60)
if left == 0 then
print("time's up")
break
end
endlocal left = 60
local label = Ui.Text({ Text = "1:00", FontSize = 32, Color = Color.new(1, 1, 1) })
Ui.Surface({ Target = Enum.SurfaceTarget.Window, Padding = 20, label }).Parent = Scene
task.spawn(function()
while left > 0 do
task.wait(1)
left -= 1
label.Text = string.format("%d:%02d", left // 60, left % 60)
end
print("time's up")
end)task.wait can wake a little late, which adds up over a long timer. For a race clock, keep the start time with os.clock() and show the difference every frame instead.
A health bar
A bar that shrinks smoothly and turns red as health drops. The width follows a computed state, and Ui.Animated eases it.
let health = Ui.State(100)
let width = Ui.Animated(Ui.Computed(fn(use) => `{use(health)}%`))
let color = Ui.Computed(fn(use) => if use(health) > 30 then $4ade80 else $ef4444)
Surface {
Target = "Window",
Padding = 20,
View {
Width = 240,
Height = 18,
Background = $1f2430,
BorderRadius = 9,
Overflow = "Hidden",
View { Width = width, Height = "100%", Background = color },
},
Parent = Scene,
}
fn damage(amount: number)
health:Set(math.max(health:Get() - amount, 0))
end
every 1 do
damage(15)
endlocal health = Ui.State(100)
local width = Ui.Animated(Ui.Computed(function(use)
return `{use(health)}%`
end))
local color = Ui.Computed(function(use)
return if use(health) > 30 then Color.fromHex("#4ade80") else Color.fromHex("#ef4444")
end)
Ui.Surface({
Target = Enum.SurfaceTarget.Window,
Padding = 20,
Ui.View({
Width = 240,
Height = 18,
Background = Color.fromHex("#1f2430"),
BorderRadius = 9,
Overflow = Enum.Overflow.Hidden,
Ui.View({ Width = width, Height = "100%", Background = color }),
}),
}).Parent = Scene
local function damage(amount: number)
health:Set(math.max(health:Get() - amount, 0))
end
task.spawn(function()
while true do
task.wait(1)
damage(15)
end
end)For a bar over a character's head, put the same view in a surface you position with camera:WorldToViewportPoint every frame, until BillboardGui arrives.
A door that slides open
A door that slides up when the player comes near and back down when they leave. A tween moves it over half a second.
let door = Part { Size = <6, 8, 1>, Position = <0, 4, -10>, Anchored = true, Color = $8b5e3c, Parent = Scene }
let closed = door.Position
let info = TweenInfo.new(0.5, Enum.EasingStyle.Quad, Enum.EasingDirection.Out)
fn slide(open: boolean)
let goal = if open then closed + <0, 7.5, 0> else closed
Tweens:Create(door, info, { Position = goal }):Play()
end
let isOpen = false
on Run.Heartbeat()
let camera = Scene.CurrentCamera :: Camera
let near = (camera.Transform.Position - closed).Magnitude < 12
if near != isOpen then
isOpen = near
slide(near)
end
endlocal door = Instance.new("Part")
door.Size = Vector3.new(6, 8, 1)
door.Position = Vector3.new(0, 4, -10)
door.Anchored = true
door.Color = Color.fromHex("#8b5e3c")
door.Parent = Scene
local closed = door.Position
local info = TweenInfo.new(0.5, Enum.EasingStyle.Quad, Enum.EasingDirection.Out)
local function slide(open: boolean)
local goal = if open then closed + Vector3.new(0, 7.5, 0) else closed
Tweens:Create(door, info, { Position = goal }):Play()
end
local isOpen = false
Run.Heartbeat:Connect(function()
local camera = Scene.CurrentCamera :: Camera
local near = (camera.Transform.Position - closed).Magnitude < 12
if near ~= isOpen then
isOpen = near
slide(near)
end
end)A new tween on the same property takes over from one still playing, so turning back halfway works. Use the player's character in place of the camera when you have one.
Clicking on parts
Turns whatever part you click yellow. The camera turns the mouse position into a ray, and Scene:Raycast finds the first part along it.
let camera = Scene.CurrentCamera :: Camera
let selected: BasePart? = nil
let previousColor = $ffffff
on Input.InputBegan(input, processed)
if processed or input.UserInputType != Enum.UserInputType.MouseButton1 then
return
end
let mouse = Input:GetMouseLocation()
let ray = camera:ViewportPointToRay(mouse.X, mouse.Y)
let hit = Scene:Raycast(ray.Origin, ray.Direction * 500)
if selected then
selected.Color = previousColor
selected = nil
end
if hit and hit.Instance:IsA("BasePart") then
let part = hit.Instance :: BasePart
previousColor = part.Color
part.Color = $facc15
selected = part
end
endlocal camera = Scene.CurrentCamera :: Camera
local selected: BasePart? = nil
local previousColor = Color.new(1, 1, 1)
Input.InputBegan:Connect(function(input: InputObject, processed: boolean)
if processed or input.UserInputType ~= Enum.UserInputType.MouseButton1 then
return
end
local mouse = Input:GetMouseLocation()
local ray = camera:ViewportPointToRay(mouse.X, mouse.Y)
local hit = Scene:Raycast(ray.Origin, ray.Direction * 500)
if selected then
selected.Color = previousColor
selected = nil
end
if hit and hit.Instance:IsA("BasePart") then
local part = hit.Instance :: BasePart
previousColor = part.Color
part.Color = Color.fromHex("#facc15")
selected = part
end
end)processed is true when the click landed on UI, so clicking a button doesn't also pick the part behind it. Pass RaycastParams to skip parts, such as the player's own character.
Walking a path
A character that walks to a goal around walls, jumping where the path says to. Pathfinding finds the route and a CharacterController walks it.
let body = Part { Size = <2, 5, 2>, Position = <0, 2.5, 0>, Parent = Scene }
let controller = CharacterController { Parent = body }
fn flatDistance(a: Vector3, b: Vector3): number
return <a.X - b.X, 0, a.Z - b.Z>.Magnitude
end
fn walkTo(goal: Vector3)
let path = Pathfinding:CreatePath({ AgentRadius = 1.5, AgentHeight = 5 })
path:ComputeAsync(body.Position, goal)
if path.Status != Enum.PathStatus.Success then
print("no way there")
return
end
for _, waypoint in path:GetWaypoints() do
let started = os.clock()
while flatDistance(waypoint.Position, body.Position) > 1 do
controller:Move(waypoint.Position - body.Position)
wait
if os.clock() - started > 3 then
controller:Move(<0, 0, 0>)
return
end
end
-- a Jump waypoint means the next leg needs a jump, such as onto a ledge.
if waypoint.Action == Enum.PathWaypointAction.Jump then
controller:Jump()
end
end
controller:Move(<0, 0, 0>)
end
Part { Size = <200, 1, 200>, Position = <0, -0.5, 0>, Anchored = true, Parent = Scene }
Part { Size = <1, 6, 20>, Position = <8, 3, 0>, Anchored = true, Parent = Scene }
spawn do
walkTo(<20, 0, 0>)
endlocal body = Instance.new("Part")
body.Size = Vector3.new(2, 5, 2)
body.Position = Vector3.new(0, 2.5, 0)
body.Parent = Scene
local controller = Instance.new("CharacterController")
controller.Parent = body
local function flatDistance(a: Vector3, b: Vector3): number
return Vector3.new(a.X - b.X, 0, a.Z - b.Z).Magnitude
end
local function walkTo(goal: Vector3)
local path = Pathfinding:CreatePath({ AgentRadius = 1.5, AgentHeight = 5 })
path:ComputeAsync(body.Position, goal)
if path.Status ~= Enum.PathStatus.Success then
print("no way there")
return
end
for _, waypoint in path:GetWaypoints() do
local started = os.clock()
while flatDistance(waypoint.Position, body.Position) > 1 do
controller:Move(waypoint.Position - body.Position)
task.wait()
-- stuck for 3 seconds on one leg: give up rather than walk into the wall forever.
if os.clock() - started > 3 then
controller:Move(Vector3.zero)
return
end
end
-- a Jump waypoint means the next leg needs a jump, such as onto a ledge.
if waypoint.Action == Enum.PathWaypointAction.Jump then
controller:Jump()
end
end
controller:Move(Vector3.zero)
end
local ground = Instance.new("Part")
ground.Size = Vector3.new(200, 1, 200)
ground.Position = Vector3.new(0, -0.5, 0)
ground.Anchored = true
ground.Parent = Scene
local wall = Instance.new("Part")
wall.Size = Vector3.new(1, 6, 20)
wall.Position = Vector3.new(8, 3, 0)
wall.Anchored = true
wall.Parent = Scene
task.spawn(walkTo, Vector3.new(20, 0, 0))To chase something that moves, compute the path again every second or so rather than every frame.
Key bindings
Named actions bound to keys and gamepad buttons, from a table you could load from saved settings. Rebinding is binding the action again.
let bindings = {
Interact = { Enum.KeyCode.E, Enum.KeyCode.ButtonX },
Inventory = { Enum.KeyCode.Tab, Enum.KeyCode.ButtonY },
}
let handlers = {
Interact = fn() => print("interact"),
Inventory = fn() => print("open the inventory"),
}
fn bindAll()
for name, keys in bindings do
Actions:BindAction(name, fn(_, state)
if state == Enum.UserInputState.Begin then
handlers[name]()
end
return Enum.ContextActionResult.Sink
end, false, table.unpack(keys))
end
end
fn rebind(name: string, key: Enum.KeyCode)
bindings[name][1] = key
bindAll()
end
bindAll()
rebind("Interact", Enum.KeyCode.F)local bindings = {
Interact = { Enum.KeyCode.E, Enum.KeyCode.ButtonX },
Inventory = { Enum.KeyCode.Tab, Enum.KeyCode.ButtonY },
}
local handlers = {
Interact = function()
print("interact")
end,
Inventory = function()
print("open the inventory")
end,
}
local function bindAll()
for name, keys in bindings do
Actions:BindAction(name, function(_, state)
if state == Enum.UserInputState.Begin then
handlers[name]()
end
return Enum.ContextActionResult.Sink
end, false, table.unpack(keys))
end
end
local function rebind(name: string, key: Enum.KeyCode)
bindings[name][1] = key
bindAll()
end
bindAll()
rebind("Interact", Enum.KeyCode.F)To save the bindings, store each key's Name and turn it back with Enum.KeyCode[name] when loading. See Actions.