Mixing Colors with weight

tabl[1] is the weight of the color, it works completely fine without the weight but when i do have it there it sort of darkens the color. I kinda get why this is happening but cant figure out another way to achieve colour mixing with weight.

function mixColors(colors)
	local r = 0
	local g = 0
	local b = 0
	local num = 0
	
	print(colors)
	for _,tabl in pairs(colors) do
		if #tabl ~= 0 then
			r += tabl[2] * tabl[1]
			g += tabl[3] * tabl[1]
			b += tabl[4] * tabl[1]
			num += 1
		end
	end
	
	r /= num
	g /= num
	b /= num
	
	print(r,g,b)
	
	return Color3.fromRGB(r,g,b)
end

Can you describe what you’re planning to use this for? Usually when you interpolate a bunch of colors you just end up with a muddy brown or something

im making a mining game and i want metals to be mixable in a crucible furnace, so i doubt it would look bad, i just need to get the weight working right.

local function MixColors(colors : {Color3}) : ({Color3}) -> (Color3)
	local t : {number} = {0, 0, 0}
	for _, color in ipairs(colors) do
		t[1] += color.R
		t[2] += color.G
		t[3] += color.B
	end
	local l : number = #colors
	for i, v in ipairs(t) do
		t[i] = v / l
	end
	return Color3.new(table.unpack(t))
end

local color : Color3 = MixColors({Color3.new(1, 0, 0), Color3.new(0, 0, 1)})
print(color.R, color.G, color.B) --0.5, 0, 0.5
local function MixColors(colors : {Color3}) : ({Color3}) -> (Color3)
	local c : {number} = {0, 0, 0}
	local t : {number} = {0, 0, 0}
	for _, color in ipairs(colors) do
		t[1] += color.R
		t[2] += color.G
		t[3] += color.B
		if color.R > 0 then c[1] += 1 end
		if color.G > 0 then c[2] += 1 end
		if color.B > 0 then c[3] += 1 end
	end
	for i, v in ipairs(t) do
		if v == 0 then continue end
		t[i] = v / math.min(1, c[i])
	end
	return Color3.new(table.unpack(t))
end

local color : Color3 = MixColors({Color3.new(1, 0, 0), Color3.new(0, 0, 1)})
print(color.R, color.G, color.B) --1, 0, 1

where does weight come into this?

In the second snippet only channels that are non-zero influence the end color.

function mixColors(colorse)
	
	local colors = {}
	
	for _,tabl in pairs(colorse) do
		if #tabl ~= 0 then
			local w = math.round(tabl[1]*10)
			print(w)
			for i = 1,w do
				table.insert(colors,tabl)
			end
		end
	end
	
	local r = 0
	local g = 0
	local b = 0
	local num = 0
	
	print(colors)
	for _,tabl in pairs(colors) do
		if #tabl ~= 0 then
			r += tabl[2]
			g += tabl[3] 
			b += tabl[4] 
			num += 1
		end
	end
	
	r /= num
	g /= num
	b /= num
	
	print(r,g,b)
	
	return Color3.fromRGB(r,g,b)
end

what I’m basically doing here is multiplying the colors depending on their weight and inserting it into a new table and then mixing those. Works perfectly!

1 Like