/**
* Animating a square.
*
*
Elie Zananiri
* CART 253, Winter 2008
*/
/* global variables */
float rectX = 0;
float rectY = 50;
int rectSize = 50;
// this value is used to calculate the distance of the step
int easeFactor = 10;
float acceptableOffset = 0.001;
boolean goToTarget;
float startX;
float startY;
float targetX;
float targetY;
color currColor;
color idleColor;
color activeColor;
/* built-in functions */
void setup() {
size(300, 300);
rectMode(CENTER);
colorMode(HSB, 360, 100, 100); // use the same ranges as the color selector
noStroke();
smooth();
goToTarget = false;
idleColor = color(54, 98, 98); // yellow
activeColor = color(2, 98, 97); // red
}
void draw() {
// motion blur
fill(0, 30);
rect(width/2, height/2, width, height);
if (goToTarget) moveSquare();
colorSquare();
drawSquare();
}
void mousePressed() {
// save the starting position
startX = rectX;
startY = rectY;
// save the target position
targetX = mouseX;
targetY = mouseY;
goToTarget = true;
}
/* custom functions */
// moves the square
void moveSquare() {
// find the distance from the mouse click to the square
float dX = targetX-rectX;
float dY = targetY-rectY;
// ease towards the target
float stepX = dX/easeFactor;
float stepY = dY/easeFactor;
// set the new square position
rectX += stepX;
rectY += stepY;
// check if the distance is small enough to consider it having arrived at the target
if (abs(dX) <= acceptableOffset && abs(dY) <= acceptableOffset) {
goToTarget = false;
}
}
// calculates the color ratio based on position
void colorSquare() {
float ratioX = (rectX-startX)/(targetX-startX);
float ratioY = (rectY-startY)/(targetY-startY);
float ratioAvg = (ratioX+ratioY)/2;
currColor = lerpColor(idleColor, activeColor, ratioAvg);
}
// draws the square
void drawSquare() {
fill(currColor);
rect(rectX, rectY, rectSize, rectSize);
}