/** * 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 targetX; float 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 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; } } // draws the square void drawSquare() { fill(255, 128, 0); // orange rect(rectX, rectY, rectSize, rectSize); }