Pick random color, animate to other random color from array, repeat? -Updated

So I am using gsap and three js my aim is to animate a light

I have an array of colors i wish to use i have code set up so 1 of these colors are picked randomly

now i can get it to pick random colors and repeat infinity … this is what I want …

now when I use onCompleteAll: change, this works all good and fine BUT it doesn’t animate the colors it just “jumps” to the next color when the duration is done so no animation it just changes straight away when the time is up

so I thought Oh well easy enough to fix i will use onComplete: change, instead now this never fires tho? so what ends up happening is the colors change and animate perfectly but only 2 of the colors from the array because the change(); function never gets fired so either does the new random value

Math.floor(Math.random() * std.length)
can anyone spot any obvious mistakes or know of any fixes?

here is my code:

 	var std = [new THREE.Color().setHex(0x009dff),
  new THREE.Color().setHex(0x001aff),
  new THREE.Color().setHex(0x4000ff),
  new THREE.Color().setHex(0x7300ff)];

var randomIndex, randomColor, tempColor, camlight3;

randomIndex = Math.floor(Math.random() * std.length); 
     randomColor = std[randomIndex];
     tempColor = randomColor;

  camlight3 = new THREE.PointLight(tempColor, 60, 80, 0.0);
        camlight3.power = 60;
        camlight3.position.x += 10;
	    camlight3.position.y += 25;
		camlight3.position.z -= 120;


  duration: 2,
  r: tempColor.r, g: tempColor.g, b: tempColor.b,
  onCompleteAll: change,
  yoyo: true,
  repeat: -1,
  repeatRefresh: true,

function change() {
     randomIndex = Math.floor(Math.random() * std.length); 
     randomColor = std[randomIndex];
     tempColor = randomColor;
     camlight3.color = tempColor;


thanks for any help

EDIT i should mention I have other animations doing on that use the oncomplete and onupdate if that matters non of the other though call change or are associated with the light


1 Like

I don’t have a gsap example, but I do have a lerp example where each object lerps to a new random colour every second.
JSFiddle : Colour lerping

1 Like