Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
✓ ANSWER ACCEPTED

Why isn't these 3 for-loops inside of eachother working?

Why isn't these 3 for-loops inside of eachother working?

I am trying to get the change the values at the same time "smoothly" by using for-loops. The reason for this is because I have another script that checks when those values gets updated, and updated the camera angle for my custom camera.

My coding is as follows:

local Configuration = game.ReplicatedStorage:WaitForChild("Configuration")

local cameraConfig = Configuration:WaitForChild("Camera")
local cameraAngleX = cameraConfig:WaitForChild("CameraOffsetX")
local cameraAngleY = cameraConfig:WaitForChild("CameraOffsetY")
local cameraAngleZ = cameraConfig:WaitForChild("CameraOffsetZ")

--//Reset camera
for x = 10,90,1 do 
	for y = 10,120,1 do
		for z = 10,0,-1 do
			wait()
			cameraAngleX = x
			cameraAngleY = y
			cameraAngleZ = z
		end
	end
end

Any help is greatly appreciated!

1 answer

✓ Accepted answer

There are two problems with your script:

  1. Whatever CameraOffsetX (and Y/Z) are, the cameraAngleX/Y/Z variables only contain a reference to them. You are replacing that reference in your for-loops - this doesn't impact the original CameraOffset objects. If the CameraOffset objects are, for instance, NumberValues, you should say cameraAngleX.Value = x
  2. When you nest for-loops (that is, you put them inside each other), the inner-most one will fully run once before the second-inner-most one will advance to its next value. Then the inner-most one will fully run again. ex, in this case, x, y, and z will be set to 10, 10, 10; then 10, 10, 9; 10, 10, 8; etc. Once it becomes 10, 10, 0, the next value combination will be 10, 11, 10; then 10, 11, 9; then 10, 11, 8; and so on. I doubt this is what you wanted.

If you're trying to get the camera to transition smoothly from one cframe to another, you might want to look into CFrame:lerp. You'll need to research how to use it if it looks like what you want.

To fix the code you have, you need to use a single for loop:

function lerp(start, goal, amount) --amount must be between 0 and 1
	return start * (1 - amount) + goal * amount
end
for i = 1, 60 do --Animation will take approximately 2 seconds since 30 'wait's can occur per second
	wait()
	local amount = i/60
	cameraAngleX.Value = lerp(10, 90, amount)
	cameraAngleY.Value = lerp(10, 120, amount)
	cameraAngleZ.Value = lerp(10, 0, amount)
end	

An even better animation might progress amount based on how much time has passed, rather than which loop iteration you're on, but this will work so long as heavy lag isn't an issue.

1 comment

0

Thank you so much! :3 This is exactly what I needed to know, and it works as a charm! :-)

This discussion is preserved as it was. New answers, comments, and votes are closed.