Exercise 6.03 Chapter 6
Vehicle & Main
Vehicle v;
void setup() { size(800, 500); v = new Vehicle(width/2, height/2); smooth(); }
void draw() { background(239);
PVector mouse = new PVector(mouseX, mouseY);
// Draw an ellipse at the mouse location fill(170); stroke(0); strokeWeight(2); ellipse(mouse.x, mouse.y, 48, 48);
// Call the appropriate steering behaviors for our agents v.seek(mouse); v.update(); v.display(); }
class Vehicle {
PVector location; PVector velocity; PVector acceleration; float r; float maxforce; // Maximum steering force float maxspeed; // Maximum speed
Vehicle(float x, float y) { acceleration = new PVector(0,0); velocity = new PVector(0,-2); location = new PVector(x,y); r = 6; float locx = location.x; if (locx>width/2){ maxspeed = 2; maxforce = 0.1; }else{ maxspeed = 8; maxforce = 0.1; }
}
// Method to update location void update() { // Update velocity velocity.add(acceleration); // Limit speed velocity.limit(maxspeed); location.add(velocity); // Reset accelerationelertion to 0 each cycle acceleration.mult(0); }
void applyForce(PVector force) { // We could add mass here if we want A = F / M acceleration.add(force); }
// A method that calculates a steering force towards a target // STEER = DESIRED MINUS VELOCITY void seek(PVector target) { PVector desired = PVector.sub(target,location); // A vector pointing from the location to the target
// Normalize desired and scale to maximum speed desired.normalize(); desired.mult(maxspeed); // Steering = Desired minus velocity PVector steer = PVector.sub(desired,velocity); steer.limit(maxforce); // Limit to maximum steering force
applyForce(steer); }
void display() { // Draw a triangle rotated in the direction of velocity float theta = velocity.heading2D() + PI/2; fill(127); stroke(0); strokeWeight(1); pushMatrix(); translate(location.x,location.y); rotate(theta); beginShape(); vertex(0, -r*2); vertex(-r, r*2); vertex(r, r*2); endShape(CLOSE); popMatrix();
} }
As previews one this time was harder. I had to relay on help of Dany in order to fish it. Almost all the code is similar because it was taken from the book and previews example.















