From 2fb959f208da22bacab479bfb35444d13a537f90 Mon Sep 17 00:00:00 2001 From: Daniel Shiffman Date: Wed, 23 Jul 2014 10:06:52 -0400 Subject: [PATCH] exercise I.3 --- chp6_agents/NOC_6_07_Separation/Vehicle.pde | 6 +-- .../Exercise_I_3_Walker_To_Mouse.pde | 20 ++++++++ .../Exercise_I_3_Walker_To_Mouse/Walker.pde | 49 +++++++++++++++++++ 3 files changed, 71 insertions(+), 4 deletions(-) create mode 100644 introduction/Exercise_I_3_Walker_To_Mouse/Exercise_I_3_Walker_To_Mouse.pde create mode 100644 introduction/Exercise_I_3_Walker_To_Mouse/Walker.pde diff --git a/chp6_agents/NOC_6_07_Separation/Vehicle.pde b/chp6_agents/NOC_6_07_Separation/Vehicle.pde index f0a5ddb9..d3e93d03 100644 --- a/chp6_agents/NOC_6_07_Separation/Vehicle.pde +++ b/chp6_agents/NOC_6_07_Separation/Vehicle.pde @@ -50,10 +50,8 @@ class Vehicle { } // Average -- divide by how many if (count > 0) { - sum.div(count); - // Our desired vector is the average scaled to maximum speed - sum.normalize(); - sum.mult(maxspeed); + // Our desired vector is moving away maximum speed + sum.setMag(maxspeed); // Implement Reynolds: Steering = Desired - Velocity PVector steer = PVector.sub(sum, velocity); steer.limit(maxforce); diff --git a/introduction/Exercise_I_3_Walker_To_Mouse/Exercise_I_3_Walker_To_Mouse.pde b/introduction/Exercise_I_3_Walker_To_Mouse/Exercise_I_3_Walker_To_Mouse.pde new file mode 100644 index 00000000..eccfde15 --- /dev/null +++ b/introduction/Exercise_I_3_Walker_To_Mouse/Exercise_I_3_Walker_To_Mouse.pde @@ -0,0 +1,20 @@ +// The Nature of Code +// Daniel Shiffman +// http://natureofcode.com + +Walker w; + +void setup() { + size(640,360); + // Create a walker object + w = new Walker(); + background(255); +} + +void draw() { + // Run the walker object + w.step(); + w.render(); +} + + diff --git a/introduction/Exercise_I_3_Walker_To_Mouse/Walker.pde b/introduction/Exercise_I_3_Walker_To_Mouse/Walker.pde new file mode 100644 index 00000000..cf71ab06 --- /dev/null +++ b/introduction/Exercise_I_3_Walker_To_Mouse/Walker.pde @@ -0,0 +1,49 @@ +// The Nature of Code +// Daniel Shiffman +// http://natureofcode.com + +// A random walker object! + +class Walker { + int x, y; + + Walker() { + x = width/2; + y = height/2; + } + + void render() { + stroke(0); + strokeWeight(2); + point(x, y); + } + + // Randomly move up, down, left, right, or stay in one place + void step() { + + float r = random(1); + // A 50% of moving towards the mouse + if (r < 0.5) { + int xdir = (mouseX-x); + int ydir = (mouseY-y); + if (xdir != 0) { + xdir /= abs(xdir); + } + if (ydir != 0) { + ydir /= abs(ydir); + } + x += xdir; + y += ydir; + } else { + int xdir = int(random(-2, 2)); + int ydir = int(random(-2, 2)); + println(xdir); + x += xdir; + y += ydir; + } + + x = constrain(x, 0, width-1); + y = constrain(y, 0, height-1); + } +} +