I'm working through an exercise from the Nature of Code which involves converting an existing program to include vectors. The original code I'm working from is that of a Walker object which tends to the right during a "random walk":
With what I've written so far, when I attempt to run the code, the Sketch tab opens up and nothing draws.
The program declares the x and y components for a Walker object, adds them, renders. And then the following:
void step()
{
int rx = int(random(1));
int ry = int(random(1));
if (rx < 0.4)
{
x++;
} else
if (rx < 0.5)
{
x--;
}
else
if (ry < 0.9)
{
y++;
}
else
{
y--;
}
}
}
Walker w;
Walker location;
Walker velocity;
void setup()
{
size(200, 200);
background(255);
Walker w = new Walker(5, 5);
Walker location = new Walker(100, 100);
Walker velocity = new Walker(2.5, 3);
}
void draw()
{
location.add(velocity);
w.step();
w.render();
}
I'm assuming you're working on this exercise in Chapter 1 of the Nature of Code book:
Exercise 1.2
Take one of the walker examples from the introduction and convert it to use PVectors.
So you want to start with the WalkerTendsToDownRight example and use vectors, right? The x and y int fields that hold the location of the walker can be replaced by a vector. I think the main sketch code can remain the same. The walker code could look something like this:
class Walker {
PVector location;
Walker() {
location = new PVector(width / 2, height / 2);
}
void render() {
stroke(0);
strokeWeight(2);
point(location.x, location.y);
}
// Randomly move right (40% chance), left (10% chance),
// down (40% chance), or up (10% chance).
void step() {
float randomDirection = random(1);
if (randomDirection < 0.4) {
location.x++;
} else if (randomDirection < 0.5) {
location.x--;
} else if (randomDirection < 0.9) {
location.y++;
} else {
location.y--;
}
location.x = constrain(location.x, 0, width - 1);
location.y = constrain(location.y, 0, height - 1);
}
}
In the Walker with vector example on GitHub, they have also used a vector for storing the move that the walker will make. With that approach, the step function could be a lot shorter (while maintaining the preference for moving right and/or down):
void step() {
PVector move = new PVector(random(-1, 4), random(-1, 4));
location.add(move);
location.x = constrain(location.x, 0, width - 1);
location.y = constrain(location.y, 0, height - 1);
}
You can even add a call to the limit function if you want your walker to keep taking small steps:
move.limit(1);