Coins: touch, debounce, respawn, leaderstats

Make a Roblox coin pickup that cannot be farmed. Follow Beacon Yard's CoinService through Touched, a per-player debounce, a distance check, a respawn timer and the leaderstats leaderboard.

Project lesson, about 70 minutes, 10 steps

By the end you can

  • Trace one coin from Touched through the server checks to the leaderstats IntValue
  • Explain why one visit pays once, and why a far touch must not burn the pickup
  • Change COIN_VALUE and predict which tests move

Before this: World building in code: MapBuilder, lighting, atmosphere, Security: never trust the client

1One step, a dozen touches

Back at m02-the-pad, the yard started with one pad and a bare script that printed every time something touched it. Walk onto that pad once and Output fills up: LeftFoot touched Pad1, LeftLowerLeg touched Pad1, RightFoot touched Pad1, and again as you shuffle.

pad.Touched:Connect(function(hit: BasePart)
	print(hit.Name .. " touched " .. pad.Name)
end)
Figure 1.1

Touched fires once for every part that starts touching, not once per player. If each touch paid 5 coins, one step would pay 50.

Touched is a bump sensor. It tells you that something bumped the part, and nothing else: not who, not how many times they meant to, not whether it was fair.

Think of it as A bump sensor

Server sideRemember: The Touched event is a bump sensor.

A player walks onto the m02 pad and stops. Why does Output show several lines?

  1. Touched fires once per body part that starts touching the pad
  2. The script is connected several times
  3. Every client also prints the touch
  4. The pad is touching the baseplate
Answer

Touched fires once per body part that starts touching the pad. Each foot and leg is a separate part, and each one fires Touched when it starts touching. The handler has to turn many bumps into one decision.

Open this step in lesson mode · Link to this step · This confused me

2CoinService pays on the server

m03-coins-count replaces the print with CoinService. It spawns a coin above each pad and pays from the coin's own Touched handler, on the server. A client cannot give itself coins, because the client never runs this code.

Figure 2.1.

Walking onto a pad: the server pays 5 and destroys the coin.

Transcript
  1. 0:00 Walking onto the pad fires Touched on the server.
  2. 0:03 The root is within 12 studs, so the server adds 5 coins.
  3. 0:07 The leaderboard IntValue updates from the profile. The coin part is destroyed.

The handler finds the player from the part that touched, using GetPlayerFromCharacter. A touch from a crate or a falling part has no player, and the handler returns early.

	local claimed = false
	local seen: { [Player]: boolean } = {}
 
	coin.Touched:Connect(function(hit: BasePart)
		if claimed then
			return
		end
		local player = playerFromHit(hit)
		if not player then
			return
		end
		if seen[player] then
			return
		end
		seen[player] = true
		claimed = true
 
		local value = coin:GetAttribute("CoinValue")
		local amount = if typeof(value) == "number" then value else Config.COIN_VALUE
		DataService.addCoins(player, amount)
		coin:Destroy()
Figure 2.2

Config.COIN_VALUE is 5. A player collects three coins from three different pads. How many coins does leaderstats show if they started at 0?

Answer

15 coins. Three coins at 5 each is 15. The amount comes from the CoinValue attribute on the coin, which falls back to Config.COIN_VALUE.

Open this step in lesson mode · Link to this step · This confused me

3Two flags make one payout

The coin keeps two guards. claimed turns true the moment anyone is paid, so later touches return at once. seen is a table keyed by player, so the same player cannot be paid twice by this coin. Guards like these are called a DebounceDebounceA guard that turns many rapid triggers into one action.Think of it as an elevator call button that ignores mashing..

A debounce is the elevator call button. Press it ten times and the elevator still comes once. The building remembers the first press and ignores the rest until the trip is over.

Think of it as An elevator button that ignores mashing

Server sideRemember: A debounce is an elevator button that ignores mashing.

Luau
local claimed = false
local seen = {}
local paid = 0
 
local function onTouch(player)
	if claimed then return end
	if seen[player] then return end
	seen[player] = true
	claimed = true
	paid += 5
end
 
for _, who in { "Ada", "Ada", "Ada", "Ben", "Ada" } do
	onTouch(who)
end
print("paid", paid)
Figure 3.1. Expected output: paid 5

In the cell above, Ben touches the coin right after Ada. Why does Ben get nothing?

  1. claimed is already true, so every later touch returns
  2. seen[Ben] is true
  3. Ben is not a player
  4. The loop skips Ben
Answer

claimed is already true, so every later touch returns. Once Ada is paid, claimed is true and the coin is about to be destroyed. Ben waits for the respawn.

Open this step in lesson mode · Link to this step · This confused me

4A touch is only a hint

At m04-two-sides the handler gained one more check. Before paying, the server measures the distance from the character's HumanoidRootPart to the coin. More than 12 studs away, it returns. That stops a forged touch from across the yard. It does not stop a cheater who teleports their own character onto the coin, because the client owns its character's position; Security: never trust the client covers why.

		-- A touch is only a hint. Check the character's root is close
		-- enough to the coin before paying.
		local character = player.Character
		local rootPart = if character then character:FindFirstChild("HumanoidRootPart") else nil
		if rootPart == nil or not rootPart:IsA("BasePart") then
			return
		end
		if (rootPart.Position - coin.Position).Magnitude > 12 then
			return
		end
		seen[player] = true
		claimed = true
Figure 4.1

Look at the order. The distance check comes before seen[player] = true. If it came after, a forged far touch would mark the player as seen and lock them out of a coin they never collected.

This handler locks honest players out after a bad touch. Which line is in the wrong place?

if claimed then return end
if seen[player] then return end
seen[player] = true
if (rootPart.Position - coin.Position).Magnitude > 12 then return end
claimed = true
Answer

Line 3: seen[player] = true. Fixed: Move seen[player] = true below the distance check. Line 3 marks the player before the request is known to be legal. A far touch then returns with seen already set, and the player can never collect that coin. Set the flag only after every check passes.

Open this step in lesson mode · Link to this step · This confused me

5leaderstats is a display copy

The number players see in the top-right list comes from a folder named exactly leaderstats under the Player, holding an IntValue named Coins. Roblox shows any value in that folder on the session leaderboard. The name must be all lowercase, or the player is not added to the board1.

local function ensureLeaderstats(player: Player, profile: Profile)
	local existing = player:FindFirstChild("leaderstats")
	if existing then
		existing:Destroy()
	end
	local leaderstats = Instance.new("Folder")
	leaderstats.Name = "leaderstats"
	local coins = Instance.new("IntValue")
	coins.Name = "Coins"
	coins.Value = profile.coins
	coins.Parent = leaderstats
	leaderstats.Parent = player
	coinStats[player] = coins
Figure 5.1

The real balance is profile.coins inside DataService, on the server. addCoins changes the profile, then copies the number into the IntValue. The HUD reads the IntValue too. If a client changes its own copy of the IntValue, only that screen changes.

Roblox Studio
Beacon Yard during Play: the HUD at the top left and the player list at the top right show the same coin total.

Select a numbered pin, or a row below, to read what it marks.

Figure 5.2.

The HUD and the player list read the same IntValue.

DataService names the folder Leaderstats with a capital L. What do players see?

local leaderstats = Instance.new("Folder")
leaderstats.Name = "Leaderstats"
leaderstats.Parent = player
  1. No coin column on the player list
  2. The same coin column as before
  3. An error in Output
  4. A column named Leaderstats
Answer

No coin column on the player list. Roblox looks for a child named exactly leaderstats. With any other name the folder is just a folder, so the list shows no stat.

Open this step in lesson mode · Link to this step · This confused me

6The server respawns the coin

After paying, the handler destroys the coin and calls task.delay with Config.COIN_RESPAWN_SECONDS, which is 4. The new coin is a new part with a new seen table, so the pad pays again. The tests shorten the wait with a workspace attribute, TestCoinRespawnSeconds. The game itself never sets it.

Figure 6.1.

Standing on the pad: the coin returns after about 4 seconds and pays again.

Transcript
  1. 0:02 The first coin is gone. Standing here does not pay again.
  2. 0:04 After 4 seconds the server spawns a new coin.
  3. 0:09 The new coin has its own debounce table, so the second touch pays another 5.

Put one pickup in the order the server runs it.

  1. Wait COIN_RESPAWN_SECONDS, then spawn a new coin
  2. Find the player and check the 12-stud distance
  3. Set seen and claimed, then add CoinValue to the profile
  4. Touched fires on the coin
  5. Destroy the coin
Answer

1. Touched fires on the coin 2. Find the player and check the 12-stud distance 3. Set seen and claimed, then add CoinValue to the profile 4. Destroy the coin 5. Wait COIN_RESPAWN_SECONDS, then spawn a new coin. Touch, checks, flags and payment, destroy, then a delayed respawn. The respawn is scheduled by the server, so a client cannot speed it up.

Open this step in lesson mode · Link to this step · This confused me

7Where the elevator picture breaks

Where does it break?“A bump sensor” is a good picture of the touched event. Where does it stop being true?

It breaks here. It fires many times for one contact, and a part moved by setting its CFrame (PivotTo) makes no bump by moving, so a drone that lands on a player standing still never fires it.

The true model. Touched fires when the physics engine sees two parts start touching through simulated movement, and at least one of them must be unanchored. It fires per part, repeatedly, and not when a script sets a CFrame so that parts overlap. Gameplay needs its own guard, and moving hazards often use a distance check instead.

The bump sensor breaks the same way: one contact can bump many times, and an anchored part moved by setting its CFrame makes no bump by moving. The elevator button works for everyone in the building. A game debounce cannot. Answer first, then open the breakdown.

Where does it break?“An elevator button that ignores mashing” is a good picture of a debounce. Where does it stop being true?

It breaks here. One button serves everyone, but a game debounce must be kept per player and on the server, or one player blocks another and an exploiter skips it.

The true model. A debounce is state the server keeps, usually per player, that says an action already happened. Checks that decide whether the action is legal run before that state is written.

Which of these are true for Beacon Yard's coin debounce?

  1. It is kept on the server, inside CoinService
  2. It is kept per player, in the seen table
  3. A LocalScript debounce would stop an exploiter
  4. One shared global cooldown would be fairer for six pads
Answer

It is kept on the server, inside CoinService; It is kept per player, in the seen table. The guard lives on the server, where clients cannot touch it, and it is keyed by player so one player's touch never blocks another's. A client-side debounce only slows down honest players.

Open this step in lesson mode · Link to this step · This confused me

8Build it: inspect and test CoinService at m06

Other ways pros do this

OptionWhat it isWhen pros pick itTrade-offs
Touched on the coinThe engine reports contact; the server checks it.Pickups, pads and triggers the player walks into. What Beacon Yard uses.Fires many times and can be faked by a client that owns its character, so it needs a debounce and a server distance check.
Spatial queryworkspace:GetPartsInPart or GetPartBoundsInBox, run on a timer or on Heartbeat.Zones that must know who is inside right now, such as capture points.You pay for every query, even when nobody is near.
ProximityPromptA key or tap the player presses near a part.Deliberate actions, such as the beacon's Start drill.Slower than walking over a coin, and not suited to many small pickups.
  • src/server/CoinService.luau
  • src/server/DataService.luau
  • src/shared/Config.luau
  • src/server/init.server.luau
  1. In the game repo, run git diff m02-the-pad m04-two-sides -- src/server/CoinService.luau src/server/DataService.luau. (Later milestones only dress the coin in an uploaded mesh; the rules stay the same.)

    You should see The diff adds CoinService.luau with the claimed and seen debounce, the 12-stud distance check, the respawn timer and DataService.addCoins, plus the leaderstats code in DataService.luau.

  2. Check out m06-drone-wrench and open src/shared/Config.luau and src/server/CoinService.luau.

    You should see Config.luau holds COIN_VALUE = 5 and COIN_RESPAWN_SECONDS = 4. CoinService.luau keeps claimed, seen, the 12-stud check and DataService.addCoins.

  3. Run rojo serve, connect Studio and press Play. Walk onto a pad.

    You should see A coin floats above each of the six pads. Walking onto one adds 5 to Coins on the player list, and a new coin appears about 4 seconds later.

  4. From the server command bar, run game.ServerScriptService.RunGameTests:Invoke().

    You should see Output prints TEST PASS coin_pickup and TEST PASS coin_respawn.

Open this step in lesson mode · Link to this step · This confused me

9Challenges

Level 1, Apprentice

Challenge

Make each coin worth 10, see which test notices, then put it back.

Start from
The game at milestone m06 (download)

Done means

  • A pickup shows +10 during Play
  • config_numbers fails with Config.luau drifted from the contract
  • COIN_VALUE is 5 again afterwards

Hints

  1. Change only COIN_VALUE in Config.luau.
  2. coin_pickup compares against Config.COIN_VALUE, so it still passes.
  3. config_numbers compares against the literal 5.

You set COIN_VALUE to 10. Which test fails?

  1. config_numbers, because it checks the literal 5
  2. coin_pickup, because it expects +5
  3. coin_respawn, because the wait changes
  4. None of them
Answer

config_numbers, because it checks the literal 5. coin_pickup adds Config.COIN_VALUE to the old score, so 10 still passes. config_numbers is the contract test that pins the course's numbers.

Level 2, Builder

Challenge

Shrink the reach to 2 studs and feel the difference, then restore 12.

Start from
The game at milestone m06 (download)

Done means

  • With the limit at 2 studs, stopping just short of a pad does not pay
  • Standing on the pad still pays
  • The limit is 12 again afterwards

Hints

  1. Change only the literal 12 in the Touched handler.
  2. Do not move the check below seen[player] = true.

Level 3, Professional

Challenge

Add one bonus coin worth 15 with its own tag and its own respawn timer, without changing the six pad coins.

Start from
The game at milestone m06 (download)
Grade it
To grade work from an earlier milestone, apply your challenge changes to a checkout based on m14-ship, which includes the Course Runner. In Studio, press Play, then run game.ServerScriptService.RunGameTests:Invoke("coins", "coins-bonus") in the server command bar. Copy the pass code from Output.

Done means

  • A part tagged BonusCoin, not Coin, with CoinValue 15, parented to Workspace.Yard
  • Collecting it pays 15 through DataService.addCoins with the same 12-stud rule
  • It respawns after 8 seconds, or TestBonusRespawnSeconds when that is set
  • The test prints TEST PASS bonus_tagged, bonus_pay, bonus_respawn and pad_respawn_separate

Hints

  1. Copy the shape of spawnCoin into a new function and call it from CoinService.start.
  2. Place it near (0, 3, 8), out of reach of the pad coins.
  3. The check is challenges/coins.luau; run it from the server script's require cache.

Open this step in lesson mode · Link to this step · This confused me

10Recap

Retiring the analogy

You no longer need “an elevator button that ignores mashing”. A debounce is state the server keeps, usually per player, that says an action already happened. Checks that decide whether the action is legal run before that state is written.

Recap

  1. Touched is a bump sensor: it fires per body part, so the server turns many bumps into one decision.
  2. A debounce that matters lives on the server and is kept per player; legality checks come before the flags are set.
  3. leaderstats is a display copy named in lowercase; DataService's profile is the real balance.

The Touched event is a bump sensor, until it fires many times for one contact, and a part moved by setting its CFrame (PivotTo) makes no bump by moving, so a drone that lands on a player standing still never fires it.

A debounce is an elevator button that ignores mashing, until one button serves everyone, but a game debounce must be kept per player and on the server, or one player blocks another and an exploiter skips it.

Next The round loop: a state machine

Open this step in lesson mode · Link to this step · This confused me