Introduction
Understanding how to use these three incredibly useful functions in Roblox Studio allows you to create neat effects! For example, you can use math.noise(x, y, z) to create cool random camera swaying effects, shaking effects, procedural movement, or math.sin(x) to create bobbing/hovering animations - which can be combined with math.cos(x) to create circular movement!
Understanding the Basics
math.noise(x, y, z): number?:
math.noise generates something called ‘Perlin noise’, that produces smooth, natural-looking random values. You commonly see this function being used for terrain, textures, and procedural generation.
Basic Usage
local value = math.noise(x, y, z)
math.noise(x, y, z)takes in 1-3 coordinates (y, z optional)- Returns a number between -1 and 1
- Same inputs always produce the same output! Perlin noise is how Minecraft is able to have identical worlds through the same seed!
Key Properties
- Smooth: Values change gradually between nearby coordinates
- Deterministic: Consistent results for same inputs
- Coherent: Similar inputs produce similar outputs
Scale Control
This is incredibly important for adjusting how ‘strong’ the noise is/amplified, and adjusting how frequent the ‘noise’ is.
- Smaller multipliers = larger, smoother features
- Larger multipliers = smaller, more detailed features
local FREQUENCY = 1 -- Adjust for how frequent/fast you want the noise to be
local AMPLITUDE = 1 -- Adjust for how amplified or strong you want the noise to be
local valueX = math.noise(x * FREQUENCY, 0, 0) * AMPLITUDE
Conclusion
math.noise is perfect for natural-looking randomness and procedural generation with spatial continuity.
math.sin(x): number
math.sin calculates the sine of an angle, producing smooth wave like oscillating values for animations and wave patterns. It is very commonly used in trigonometry
Basic Usage
local value = math.sin(angle)
- Takes angle in radians (not degrees)
- Returns number between -1 and 1
- Creates smooth wave pattern
Key Properties
- Periodic: Repeats every 2pi radians (360 degrees)
- Smooth: Creates flowing curves
- Oscillating: Goes from -1 to 1 and back
Scale Control
You can multiply the angle to control speed/frequency, and multiply the result of math.sin to increase the range/amplitude
- Larger Multipliers = faster oscillation
- Smaller multipliers = slower oscilliation
local AMPLITUDE = 1 -- Adjust for higher range or more strength
local FREQUENCY = 1 -- Adjust for faster or slower oscillation
local sinX = math.sin(elapsed * FREQUENCY) * AMPLITUDE
Conclusion
math.sin is perfect for smooth animations, wave effects and circular motion in games
math.cos(x): number
math.cos does not need its’ own explanation, as it follows the same principles as math.sin - just shifted 90 degrees (pi/2 radians).
Here are some of the key differences:
math.cos(0)= 1 (starts at peak)math.sin(0)= 0 (starts at middle)
Same usage applies - time based animation, waves, oscillation. The only thing is, math.sin is primarily used for vertical motion, while math.cos is primarily used for horizontal motion, but honestly you can use math.cos for vertical movement, and math.sin for horizontal movement, it doesn’t really matter.
Creating the neat effects
Here is the fun part now, using these functions in practice to create cool effects!
Camera Shake/Sway
-- Inside a LocalScript in StarterCharacterScripts...
-- We will need RunService
local RunService = game:GetService("RunService")
-- VARIABLES --
-- We need the current camera to adjust its' CFrame
local camera = workspace.CurrentCamera
-- Next, we need to create a variable that stores a number. It will start at 0, and get incremented each
-- frame by RunService to create a 'stop-watch'. This will act as the input for our noise on each axis.
local elapsed = 0
-- CONSTANTS --
-- Define some constant values...
local STRENGTH = 2 -- This is how strong we want the noise to be, or the range of the noise
local FREQUENCY = 1 -- This is how fast/slow we want the noise to be
-- Next, we will connect to the RunService:BindToRenderStep() method. (You can also use Heartbeat)
-- :BindToRenderStep gives us the deltaTime.
-- deltaTime is the time between each frame for the client.
RunService:BindToRenderStep("CAMERA_SWAY", Enum.RenderPriority.Camera.Value, function(dt: number)
-- Inside here, which runs every frame, we need to increment 'elapsed' by dt (deltaTime)
elapsed += dt
-- Next, we can create an offset Vector3
local offset = Vector3.new(
-- Each axis, we will utilize math.noise(), and apply our constant values like explained previously
math.noise(elapsed * FREQUENCY, 0, 0), -- X axis
math.noise(0, elapsed * FREQUENCY, 0), -- Y axis
math.noise(0, 0, elapsed * FREQUENCY) -- Z axis
) * STRENGTH -- This multiplies each axis by 'STRENGTH' automatically for us!
-- Finally, we can multiply our cameras' CFrame by itself then by a new CFrame that takes in a Vector3
camera.CFrame *= CFrame.new(offset)
end)
This creates a subtle camera shake effect or sway effect using the Perlin noise. It tracks elapsed time each frame, then uses math.noise with different coordinates for each axis (X, Y, Z) to generate smooth, random camera movement. The STRENGTH constant controls shake intensity, while FREQUENCY controls how fast the sway changes. The noise-generated offset is then applied to the camera’s CFrame position each frame, creating natural-looking camera sway rather than silly looking random movement.
We can do even more with this! What if we wanted the strength to be stronger based on the player’s velocity/speed? Well here is how we can do that.
In the same LocalScript:
-- Inside a LocalScript in StarterCharacterScripts...
-- We will need 'RunService'
local RunService = game:GetService("RunService")
-- NEW - We need the 'Players' service for getting the local player
local Players = game:GetService("Players")
-- VARIABLES --
-- We need the current camera to adjust its' CFrame
local camera = workspace.CurrentCamera
-- NEW - For our velocity based strength adjustment, we will need the root of the player's character
local player = Players.LocalPlayer
local char = player.Character or player.CharacterAdded:Wait()
local root: Part = char:WaitForChild("HumanoidRootPart") -- you might want to type annotate this as 'Part'
-- Next, we need to create a variable that stores a number. It will start at 0, and get incremented each
-- frame by RunService to create a 'stop-watch'. This will act as the input for our noise on each axis.
local elapsed = 0
-- CONSTANTS --
-- Define some constant values...
local STRENGTH = 2 -- This is how strong we want the noise to be, or the range of the noise
local FREQUENCY = 1 -- This is how fast/slow we want the noise to be
-- NEW - Constant value for controlling how much velocity affects the strength
local VELOCITY_SCALE = 6
-- Next, we will connect to the RunService:BindToRenderStep() method. (You can also use Heartbeat)
-- :BindToRenderStep gives us the deltaTime.
-- deltaTime is the time between each frame for the client.
RunService:BindToRenderStep("CAMERA_SWAY", Enum.RenderPriority.Camera.Value, function(dt: number)
-- Inside here, which runs every frame, we need to increment 'elapsed' by dt (deltaTime)
elapsed += dt
-- NEW: Get the magnitude of 'root' 'AssemblyLinearVelocity'
local velocityMagnitude = root.AssemblyLinearVelocity.Magnitude
-- Next we will get the total strength by adding our base 'STRENGTH' value to the 'velocityMagnitude',
-- divided by our 'VELOCITY_SCALE'
local totalStrength = STRENGTH + velocityMagnitude / VELOCITY_SCALE
-- Next, we can create an offset Vector3
local offset = Vector3.new(
-- Each axis, we will utilize math.noise(), and apply our constant values like explained previously
math.noise(elapsed * FREQUENCY, 0, 0), -- X axis
math.noise(0, elapsed * FREQUENCY, 0), -- Y axis
math.noise(0, 0, elapsed * FREQUENCY) -- Z axis
) * totalStrength -- NEW - Instead of multiplying by 'STRENGTH' multiply by 'totalStrength' that we calculated
-- Finally, we can multiply our cameras' CFrame by itself then by a new CFrame that takes in a Vector3
camera.CFrame *= CFrame.new(offset)
end)
What we are doing here is, we are added velocity-based camera sway, instead of a fixed strength. Now the camera shake intensity increases based on how fast the player is moving. It gets the player’s HumanoidRootPart.AssemblyLinearVelocity.Magnitude (speed) and adds it to the base strength using the VELOCITY_SCALE constant as a divisor. So basically when running/jumping, the camera shakes more intensely than when standing still!
BUT, there is an issue, if you couldn’t already tell, it changes very rapidly and is too responsive! This is because AssemblyLinearVelocity is instant.
To fix this, here is how we can modify our previous script:
-- Inside a LocalScript in StarterCharacterScripts...
-- We will need 'RunService'
local RunService = game:GetService("RunService")
-- We need the 'Players' service for getting the local player
local Players = game:GetService("Players")
-- VARIABLES --
-- We need the current camera to adjust its' CFrame
local camera = workspace.CurrentCamera
-- For our velocity based strength adjustment, we will need the root of the player's character
local player = Players.LocalPlayer
local char = player.Character or player.CharacterAdded:Wait()
local root: Part = char:WaitForChild("HumanoidRootPart") -- you might want to type annotate this as 'Part'
-- Next, we need to create a variable that stores a number. It will start at 0, and get incremented each
-- frame by RunService to create a 'stop-watch'. This will act as the input for our noise on each axis.
local elapsed = 0
-- NEW - New variable that holds our smoothed velocity
local smoothedVelocity = 0
-- CONSTANTS --
-- Define some constant values...
local STRENGTH = 2 -- This is how strong we want the noise to be, or the range of the noise
local FREQUENCY = 1 -- This is how fast/slow we want the noise to be
-- Constant value for controlling how much velocity affects the strength
local VELOCITY_SCALE = 6
-- NEW - Constant value for how smooth we want the strength to adjust based on velocity
local VELOCITY_SMOOTHING = 5 -- Lower values are more smooth but take a longer time, while higher values
-- are more snappy
-- Next, we will connect to the RunService:BindToRenderStep() method. (You can also use Heartbeat)
-- :BindToRenderStep gives us the deltaTime.
-- deltaTime is the time between each frame for the client.
RunService:BindToRenderStep("CAMERA_SWAY", Enum.RenderPriority.Camera.Value, function(dt: number)
-- Inside here, which runs every frame, we need to increment 'elapsed' by dt (deltaTime)
elapsed += dt
-- Get the magnitude of 'root' 'AssemblyLinearVelocity'
local velocityMagnitude = root.AssemblyLinearVelocity.Magnitude
-- NEW - Instead of using 'velocityMagnitude' directly in 'totalStrength', set 'smoothedVelocity' and use
-- 'math.lerp' to smoothly interpolate to our 'velocityMagnitude', using our 'VELOCITY_SMOOTHING' * 'dt'
smoothedVelocity = math.lerp(smoothedVelocity, velocityMagnitude, VELOCITY_SMOOTHING * dt)
local totalStrength = STRENGTH + smoothedVelocity / VELOCITY_SCALE
-- Next, we can create an offset Vector3
local offset = Vector3.new(
-- Each axis, we will utilize math.noise(), and apply our constant values like explained previously
math.noise(elapsed * FREQUENCY, 0, 0), -- X axis
math.noise(0, elapsed * FREQUENCY, 0), -- Y axis
math.noise(0, 0, elapsed * FREQUENCY) -- Z axis
) * totalStrength -- Instead of multiplying by 'STRENGTH' multiply by 'totalStrength' that we calculated
-- Finally, we can multiply our cameras' CFrame by itself then by a new CFrame that takes in a Vector3
camera.CFrame *= CFrame.new(offset)
end)
What we are doing here is simply using math.lerp to smoothly interpolate to our velocityMagnitude variable. VELOCITY_SMOOTHING determines how smooth it interpolates.
Here’s a video showcasing what this script does!
Camera Sway Showcase
Breathing Animation
We can use math.sin to create a breathing effect of a Part!
-- In a Server Script attached to a part...
-- Once again, we will need 'RunService'
local RunService = game:GetService("RunService")
-- VARIABLES --
local part = script.Parent -- The part to animate
local angle = 0 -- Time counter - acts as the angle of 'X' to be used in math.sin
-- We need to capture the startSize of 'part'
local startSize = part.Size
-- CONSTANTS --
local FREQUENCY = 2 -- How fast the breathing is
local STRENGTH = 1 -- How heavy the breathing is
-- Since were on server we can connect to the '.Heartbeat' event of 'RunService'
RunService.Heartbeat:Connect(function(dt) -- returns deltaTime
angle += dt -- Increment 'angle' by 'dt'
-- Get the result of 'math.sin', will be used for the X, Y and Z coordinates
local sinOffsetXYZ = math.sin(angle * FREQUENCY) * STRENGTH
-- Add the 'sinOffset' since 'part.Size' is a Vector3
part.Size = startSize + Vector3.new(sinOffsetXYZ, sinOffsetXYZ, sinOffsetXYZ)
end)
Here’s a video showcasing our breathing effect:
Breathing Effect Showcase
Floating/Bobbing motion:
We can also use math.sin to create a bobbing effect! It’s very similar to the breathing effect, except we are using Position instead of Size!
-- In a Server Script attached to a part...
-- Once again, we will need 'RunService'
local RunService = game:GetService("RunService")
-- VARIABLES --
local part = script.Parent -- The part to animate
local angle = 0 -- Time counter - acts as the angle of 'X' to be used in math.sin
-- We need to capture the start Position of 'part'
local startPosition = part.Position
-- CONSTANTS --
local FREQUENCY = 2 -- How fast the bobbing is
local HEIGHT = 2 -- Amplitude/Height of the bobbing
-- Since were on server we can connect to the '.Heartbeat' event of 'RunService'
RunService.Heartbeat:Connect(function(dt) -- returns deltaTime
angle += dt -- Increment 'angle' by 'dt'
-- A bobbing motion only needs a Y coordinate, as we are adjusting the height of 'part'!
local sinOffsetY = math.sin(angle * FREQUENCY) * HEIGHT
-- Add the 'sinOffsetY' to the Y axis, and zero out all others!
part.Position = startPosition + Vector3.new(0, sinOffsetY, 0)
end)
This creates a cool bobbing effect of a part!
Here’s a video showcasing the bobbing motion:
Bobbing Motion
Part Spiral
You can also create a spiral of parts using math.sin, math.cos, combined with a for loop!
-- In a server script in ServerScriptService...
local RunService = game:GetService("RunService") -- RunService for waiting until next frame in the for loop
-- VARIABLES --
-- CONSTANTS --
local RADIUS = 20 -- This is the amplitude of math.sin and math.cos, in other words, the radius
local REVOLUTIONS = 20 -- 20 Full circle revolutions
local PART_COUNT = 5000 -- How many parts we want the spiral to have
local PART_SIZE = Vector3.new(2, 2, 2) -- The size of our parts
local HEIGHT_OFFSET = 30 -- Vertical offset to lift the spiral above ground
local REVOLUTION_X_SCALAR = 5 -- The length on the x axis per revolution (stretches spiral horizontally)
-- Calculate some constants...
-- Total angle for all revolutions divided by number of parts = angle between each part
local ANGLE_INCREMENT = (math.pi * 2 * REVOLUTIONS) / PART_COUNT
-- Just a helper function for constructing a part and applying properties
local function newPart(properties: {[string]: any})
local part = Instance.new("Part")
-- Apply all properties from the table to the part
for property, value in pairs(properties) do
part[property] = value
end
return part
end
-- Create spiral by looping through each part position
for i = 1, PART_COUNT do
-- Calculate current angle based on loop iteration
local angle = (i-1) * ANGLE_INCREMENT
-- X position increases linearly (creates horizontal stretch)
local x = angle * REVOLUTION_X_SCALAR
-- Y position oscillates up and down using sine wave + offset
local y = math.sin(angle) * RADIUS + HEIGHT_OFFSET
-- Z position oscillates back and forth using cosine wave
local z = math.cos(angle) * RADIUS
-- Create part with calculated position and properties
newPart({
Anchored = true, -- Prevent physics movement
Size = PART_SIZE,
Material = Enum.Material.Neon, -- Glowing effect
Color = Color3.fromRGB(64, 127, 0), -- Green color
Position = Vector3.new(x, y, z),
Parent = workspace -- Add to game world
})
-- Wait one frame before creating next part (prevents lag)
RunService.Heartbeat:Wait()
end
This may look a bit confusing, but what this script does is it creates a 3D spiral using math.sin for the y-axis, math.cos for the z-axis, and the x-axis increases linearly. PART_COUNT determines density or how detailed the spiral is, RADIUS controls width, REVOLUTIONS sets how many full circles.
Please note that this probably shouldn’t be used in an actual application, it is incredibly demanding due to all the parts being added, it just looks quite cool.
3D Part Spiral
Natural-Looking Random UI Movement:
This next script uses math.noise again to make a GUI/UI on the screen move in natural-looking randomness. Copy & Pastable, as UI is created directly in the script!
-- Services needed...
local RunService = game:GetService("RunService")
local Players = game:GetService("Players")
-- VARIABLES --
-- We need the local plaeyr's Gui
local player = Players.LocalPlayer
local playerGui = player:WaitForChild("PlayerGui")
-- ScreenGui creation
local gui = Instance.new("ScreenGui")
gui.Parent = playerGui
gui.Name = "TextShowcase"
-- Frame creation
local frame = Instance.new("Frame")
frame.Parent = gui
frame.Name = "TextContainer"
frame.AnchorPoint = Vector2.new(0.5, 0.5)
frame.Size = UDim2.fromScale(0.2, 0.1)
frame.Position = UDim2.fromScale(0.5, 0.5) -- Start in middle of screen
frame.BackgroundTransparency = 1
-- TextLabel creation
local textLabel = Instance.new("TextLabel")
textLabel.Parent = frame
textLabel.AnchorPoint = Vector2.new(0.5, 0.5)
textLabel.Name = "Text"
textLabel.Text = "Cool Text!"
textLabel.Size = UDim2.fromScale(1, 1)
textLabel.Position = UDim2.fromScale(0.5, 0.5)
textLabel.BackgroundTransparency = 1
textLabel.TextScaled = true
textLabel.Font = Enum.Font.FredokaOne
textLabel.TextColor3 = Color3.fromRGB(255, 255, 255)
-- UIStroke
local uiStroke = Instance.new("UIStroke")
uiStroke.Parent = textLabel
uiStroke.Color = Color3.fromRGB(112, 112, 112)
uiStroke.Thickness = 3
-- Capture elapsed
local elapsed = 0
-- Capture the start position of 'frame'
local startPos = frame.Position
-- CONSTANTS --
local STRENGTH = 0.5
local FREQUENCY = 0.25
-- Connect to RunService.Heartbeat for simplicity
RunService.Heartbeat:Connect(function(dt)
elapsed += dt
local offset = UDim2.fromScale(
-- We only need X and Y, no Z since it's 2D
math.noise(elapsed * FREQUENCY, 0) * STRENGTH,
math.noise(0, elapsed * FREQUENCY) * STRENGTH
)
frame.Position = startPos + offset
end)
In this LocalScript, we are creating UI elements necessary, and then connecting to RunService.Heartbeat event. It tracks elapsed time as usual, and uses math.noise with separate X/Y coords to create the smooth 2D offset for ‘fframe’. The text continuously ‘shakes’ or ‘sways’ around its starting position based on the STRENGTH and FREQUENCY.
Here’s a video showcasing it:
UI Noise Based Movement
Blob-like Part Sizing
This next script makes a part size on all axes using math.noise to create a blob like motion.
It looks very cool!
-- In a server script attached to a Part
-- SERVICES --
local RunService = game:GetService("RunService")
-- VARIABLES --
local part = script.Parent
local startSize = part.Size
local elapsed = 0
-- CONSTANTS --
local STRENGTH = 3 -- Strength of the blob motion
local FREQUENCY = 1 -- Speed of the blob motion
-- Connect to 'RunService.Heartbeat'
RunService.Heartbeat:Connect(function(dt)
elapsed += dt
local offset = Vector3.new(
math.noise(elapsed * FREQUENCY, 0, 0),
math.noise(0, elapsed * FREQUENCY, 0),
math.noise(0, 0, elapsed * FREQUENCY)
) * STRENGTH
part.Size = startSize + offset
end)
It works quite similar to the other 3-axis based math.noise scripts, except we’re using size.
Here’s a video:
Blob Motion
Overall Conclusion
I hope you learned something from this tutorial! The possibilities are quite endless with these 3 powerful functions! Go ahead, open a script and play around with them, it’s lots of fun.
If you enjoyed this tutorial please consider liking the post, and give any feedback of what I could’ve done better - as this is my first tutorial!