/** * 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; boolean goToTarget; int targetX; int targetY; /* built-in functions */ void setup() { size(300, 300); rectMode(CENTER); noStroke(); smooth(); goToTarget = false; } void draw() { background(0); if (goToTarget) moveSquare(); drawSquare(); } void mousePressed() { targetX = mouseX; targetY = mouseY; goToTarget = true; } /* custom functions */ // moves the square void moveSquare() { // find the distance from the mouse click to the square int dX = targetX-rectX; int dY = targetY-rectY; // ease towards the target int stepX = dX/easeFactor; int 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) <= easeFactor && abs(dY) <= easeFactor) { goToTarget = false; } } // draws the square void drawSquare() { fill(255, 128, 0); // orange rect(rectX, rectY, rectSize, rectSize); }