Simple Sine Wave

I had a few people ask me to go more in-depth on how to make a simple sine wave.
This might seem really easy to some people, but simple things like this make it fun to learn programming. Learning by doing is the best form of learning.

I’ve written this code with the beginner in mind. As such, I’ve kept everything as easy to understand as possible. I don’t delve too much into tables, or even pairs/ipairs. This code isn’t meant to be computationally efficient, just easy to read and understand.

-- Create a folder to store all our parts
PartsFolder = Instance.new("Folder")
-- Place the folder inside workspace (see Explorer View window)
PartsFolder.Parent = workspace

-- Creating parts using a "for loop"
for loopNumber=1,10 do
	
	Part = Instance.new("Part") -- Create a Part
	Part.Name = loopNumber.."Part" -- Set the name property
	Part.Anchored = true -- Anchor the part
	Part.Size = Vector3.new(1,1,1) -- Set the Part's size
	Part.Position = Vector3.new(0,loopNumber,0) -- Position the part so they're all ontop of eachother
	Part.Material = "Wood" -- Set the material
	Part.Parent = PartsFolder -- Put the part inside the folder we created earlier

	-- Set the color property to be random
	-- (Try setting hue to a static number! Ex: hue = 70)
	local hue = math.random(1,100)
	Part.Color = Color3.fromHSV(hue/100, 0.5, 1)
	
end

-- Infinite loop
while true do
	
	-- Make a delay so it'll pause about every 0.01 seconds (so we can see it and it won't crash)
	wait(0.01) 
	
	-- get curret time in seconds
	local currentTime = tick() 
	
	-- Another for loop
	for loopNumber=1,10 do
		
		-- Find the part inside the folder
		local Part = PartsFolder:FindFirstChild(loopNumber.."Part")
		
		-- Use sine opperator, with an offset of loopNumber
		-- (Try multiplying loopNumber by something! Ex: X = math.sin(currentTime+loopNumber*2)
		local X = math.sin(currentTime+loopNumber)
		
		-- Set the position using this X value. Leave the other position values the same.
		Part.Position = Vector3.new(X,Part.Position.Y,Part.Position.Z)
		
	end
	
end

Click here to open Studio and see it in action.

UwU
hope this helps

Post any related questions below and I’ll try to respond to them.

9 Likes

Very cool, also if you replace sin with cos it will do the inverse, and if you replace it with tan you get some very cursed stuff

1 Like

Pretty cool
robloxapp-20210307-0845408.wmv

1 Like

You had it in a gui, how do I do that?
Btw Cool!