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

How can I transition between random colors?

I can use

	PointLight.Color = Color3.new(math.random(),math.random(),math.random())

to generate random light colors. But if I try it again, it might give me a vastly different shade than what it picked before. How can I create a smooth gradient-like transition between one random color to the next?

2 answers

✓ Accepted answer

This is called interpolating (smoothly moving between two options).

We first generate both results, and then figure out how far in time we are between the two. If we're 80% through the transitioning time, we figure out a way to be 80% towards the second color.


The simplest way to interpolate is called linear interpolation. It's called linear since the rate is constant through the transition, so the graph of any of the values is a line.


If we use ROBLOX's Vector3s to store the colors, it becomes a little briefer to do the math, so that's what I'll do.

begin = Vector3.new(math.random(),math.random(),math.random())
finish = Vector3.new(math.random(),math.random(),math.random())

startTime = tick()
duration = 5 -- seconds

while tick() - startTime < duration do
	local progress = (tick() - startTime) / duration
	-- progress is now between 0 (completely `begin` color)
	-- and 1 (completely `end` color)
	local intermediate = finish * progress + ( 1 - progress ) * begin
	-- The above is just a "weighted average" of `finish` and `begin`
	local color = Color3.new(intermediate.x, intermediate.y, intermediate.z)
	-- Use color3 for whatever
	wait()
end

To make this loop, we just have to make a new finish but move finish into begin:

begin, finish = finish, Vector3.new(math.random(),math.random(),math.random())
-- follow the previous snippet,
-- then wrap the whole thing in a `while true do` loop

2 comments

0

You can use Color3 Objects directly, since you can access the components as c3.r, c3.g, and c3.b. Directly equivalent to v3.x, v3.y, v3.z

2

Yes, but you lose the ability to use + and *, meaning the math becomes 3 times longer than necessary.

First off, you never described where PointLight is Do either

local PL = game.Workspace.PointLight

so for BrickColor all you would do is

PL.BrickColor = BrickColor:Random()

But you want a PointLight Color so try this ( not sure if this is correct, just my guess )

PL.Color = Color:Random()

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