RunService weird math


  1. What do you want to achieve?
    I want to know what this math does.

  2. What is the issue?
    I suck at maths.

  3. What solutions have you tried so far?
    I have tried to look for info but I couldn’t.

I was cheking some models of the Toolbox and I found this:

local r = game:GetService("RunService")
local last_sound_time = r.Stepped:Wait()

local now = r.Stepped:Wait()
	if (now - last_sound_time > .1) then
		Ball.Boing:Play()
		last_sound_time = now
	else
		return
	end

…and I don’t understand what it does, because I’m really bad at these maths. Now I’m looking for an explanation of what this does, maybe it checks if a certain amount of time passed? And if it is that, why should I use it instead of os.time() and tick()?

It’s the Super Ball model btw so it’s in the Toolbox if you wanna check it.

Any help is appreciated thanks.

The first argument returned by the RunService.Stepped Event is essentially just time(), which is updated every RunService.Stepped. It seems a bit much just to grab time() but I guess that’s their preference.

All the code is doing is comparing the last sound time to the current time and checking if its greater than .1 seconds, if it is, set the last sound time to now and play the sound.

1 Like

So it’s just comparing time? Is using RunService for this just a preference or does it have any advantage? Thanks btw

Hello! I’ll give you a breakdown of what this script does.

Simple explanation:
For whatever reason, it waits two frames, and gets the time elapsed for each one. After that, it subtracts both of those times and checks if the difference of the two is greater than 0.1s. If that’s the case, it plays the Boing sound. If I’d take a random guess, it’s a strange way to detect a rendering lag spike.

You can find the documentation for RunService.Stepped here.
(RunService.Stepped returns the time elapsed from the previous rendered frame, and fires before any physics simulation runs).

Also, I can’t seem to find the model in the toolbox. Would you mind linking it please? There might be some more relevant code there so I can tell you more about it’s functionality.

.
Edit: Despite this being marked as the solution, please refer to @Cozmicweb’s answer as it describes the purpose of the code shown. Thanks!

2 Likes

In the full script, this code is part of a BasePart.Touched event. Whenever the ball touches the ground, it plays the sound Ball.Boing. The provided code adds a debounce to prevent the bounce sound from playing constantly when the ball is rolling on the floor or bouncing off walls rapidly.

3 Likes

There isn’t that much, tbh. I understand the rest of the code, but here’s the link anyway.
The code is very messy, I wonder if these things were actually made by Roblox.
Thanks for your explanation, you deserve the solution.

Thanks @Cozmicweb and @Youtub5005 too

3 Likes

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.