PVectors are a good way of targeting and animating objects. It will work best with OOP but can be used without.
See, below for a basic example:
here is some code I wrote based on Daniel Shiffman's Zoog character from his Learning Processing book.
- class Zoog {
- String name;
- PVector loc;
- PVector vel;
- float topSpeed;
- float w;
- float h;
- float s; // scale
- float r; // rotation
- color c;
- color cMouseOver;
- color cMouseDown;
-
-
- Zoog() {
- loc = new PVector(width/2, height/2);
- vel = new PVector(0,0);
- w = 30;
- h = 60;
- s = 1.0; // scale
- topSpeed = 2.0;
- c = color(255,0,0);
- cMouseOver = c + color(255);
- cMouseDown = color(c, 128);
- }
-
- Zoog(PVector startLoc) {
- this();
- loc = startLoc;
- }
-
- Zoog(float startX, float startY) {
- this(new PVector(startX, startY));
- }
- Zoog(PVector startLoc, float wVal, float hVal) {
- this();
- loc = startLoc;
- w = wVal;
- h = hVal;
- }
- void setLoc(PVector newLoc) {
- loc = newLoc;
- }
-
- void setLoc(float newX, float newY) {
- setLoc(new PVector(newX, newY));
- }
- void display() {
- ellipseMode(CENTER);
- if (within(mouseX, mouseY) && mousePressed) fill(cMouseDown);
- else if (within(mouseX, mouseY)) fill(cMouseOver);
- else fill(c);
- ellipse(loc.x,loc.y, w*s, h*s);
- }
-
- void target(PVector targetV) {
- // derived from Daniel Shiffman at http://processing.org/learning/pvector/
- PVector dir = PVector.sub(targetV,loc); // Find vector pointing towards mouse
- dir.normalize(); // Normalize
- dir.mult(0.5); // Scale
- PVector acceleration = dir; // Set to acceleration
- // Motion 101! Velocity changes by acceleration. Location changes by velocity.
- vel.add(acceleration);
- vel.limit(topSpeed);
- }
-
- void calc() {
- vel.limit(topSpeed);
- loc.add(vel);
- }
- }
Basically for each time you run through loop, you would call zoog.calc(); then zoog.display();
First you set the target with zoog.target(new PVector(mouseX, mouseY);
Good luck!