/**
* Animating a square.
*
*
Elie Zananiri
* CART 253, Winter 2008
*/
/* global variables */
int rectX = 0;
int rectY = 50;
int rectSize = 50;
// this value is used to calculate the distance of the step but
// also to determine the minimum offset to reach the target
int easeFactor = 10;
int targetLeft;
int targetRight;
int currTarget;
/* built-in functions */
void setup() {
size(300, 300);
noStroke();
smooth();
targetLeft = 0;
targetRight = width-rectSize;
setTarget(targetLeft);
}
void draw() {
background(0);
moveSquare();
drawSquare();
}
/* custom functions */
// sets the target x position of the square
void setTarget(int newTarget) {
currTarget = newTarget;
}
// moves the square
void moveSquare() {
int stepX = (currTarget-rectX)/easeFactor;
rectX = rectX + stepX;
if ((rectX-targetLeft) <= easeFactor) {
setTarget(targetRight);
} else if ((targetRight-rectX) <= easeFactor) {
setTarget(targetLeft);
}
}
// draws the square
void drawSquare() {
fill(255, 128, 0); // orange
rect(rectX, rectY, rectSize, rectSize);
}