I have a grid of tiles that slowly change colors between red and green. How do I make the color change speed be dependent on mouseX such that small mouseX equals faster color changes.
function colorGrid(){
var stepSize = 20;
var green = color(0, 255, 0);
var red = color(255, 0, 0);
for(var x=0;x<25;x++){
for(var y=0;y<25;y++){
var tX = (x*stepSize+frameCount)*0.003;
var tY = (y*stepSize+frameCount)*0.003;
var t = noise(tX, tY);
var c = lerpColor(green, red, t);
fill(c);
noStroke();
rect(x*stepSize,y*stepSize,stepSize,stepSize);
}
}
}
What you want to change is the rate at which you move in the noise space. For now you use frameCount
to move temporally in this space.
So to change the speed you need to play with frameCount
. One way to do it is to map mouseX
between frameCount * 1
(your current behavior) and frameCount * X
where X > 1
.
function colorGrid(){
var stepSize = 20;
var green = color(0, 255, 0);
var red = color(255, 0, 0);
// Creating the factor
const temporalOffsetFactor = map(mouseX, 0, width, 1, 50);
for(var x=0;x<25;x++){
for(var y=0;y<25;y++){
var tX = (x*stepSize+frameCount*temporalOffsetFactor)*0.003; // Using the new factor
var tY = (y*stepSize+frameCount*temporalOffsetFactor)*0.003;
var t = noise(tX, tY);
var c = lerpColor(green, red, t);
fill(c);
noStroke();
rect(x*stepSize,y*stepSize,stepSize,stepSize);
}
}
}
See it in action here
Edit To avoid the map "jumping" when you move the mouse a possible solution is to debouce mouseX to get its value only every X ms (I found that 500ms works quite well). So you could add this to your code before the call to setup()
let debouncedMouseX = 1;
setInterval(() => (debouncedMouseX = mouseX), 1000);
and replace mouseX
by debouncedMouseX
in the line const temporalOffsetFactor = map(mouseX, 0, width, 1, 50);
That might not be ideal but it can work. I updated my codepend accordingly.