I am learning P5.JS with "The Nature of Code", and trying out the first example code.
let walker;
let bg_color_x = 255;
let bg_color_y = 51;
let bg_color_z = 153;
let stroke_color_x = 51;
let stroke_color_y = 51;
let stroke_color_z = 204;
let stroke_weight = 10;
let random_number_for_walking = 5;
function setup() {
var cnv = createCanvas(windowWidth, windowHeight);
cnv.style('display', 'block');
background(bg_color_x, bg_color_y, bg_color_z);
walker = new Walker();
}
function draw() {
walker.step();
walker.render();
}
class Walker {
constructor() {
this.x = width / 2;
this.y = height / 2;
}
render() {
stroke(stroke_color_x, stroke_color_y, stroke_color_z);
strokeWeight(stroke_weight);
point(this.x, this.y);
}
step() {
var choice = floor(random(random_number_for_walking));
if (choice === 0) {
// this.x++;
this.x = this.x + stroke_weight;
} else if (choice == 1) {
// this.x--;
this.x = this.x - stroke_weight;
} else if (choice == 2) {
// this.y++;
this.y = this.y + stroke_weight;
} else {
// this.y--;
this.y = this.y - stroke_weight;
}
this.x = constrain(this.x, 0, width - stroke_weight);
this.y = constrain(this.y, 0, height - stroke_weight);
}
}
function windowResized() {
resizeCanvas(windowWidth, windowHeight);
background(bg_color_x, bg_color_y, bg_color_z);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.4.0/p5.min.js"></script>
However, no matter how many times I run it, the art settles at the top of the window. For example, like this.
How can I fix this? Is there a way to make it go left or right when it hits one of the four borders?
Your random_number_for_walking is wrong!
Your step function has 4 paths:
step() {
var choice = floor(random(random_number_for_walking));
if (choice === 0) {
// Right
} else if (choice == 1) {
// Left
} else if (choice == 2) {
// Down
} else {
// Up
}
// ...
}
But your random_number_for_walking is 5 and random(number) gives you a number between [0, number), so in your case: 0, 1, 2, 3, 4.
And if you look closer, you do not handle choice == 3, with that else you are actually handling choice == 3 || choice == 4.
This makes it so its more probable that your Walker moves up than down.
Handling correctly the last choice and reducing random_number_for_walking to 4 will solve the issue.