Estoy aprendiendo P5.JS con "La naturaleza del código" y probando el primer código de ejemplo.
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>
Sin embargo, no importa cuántas veces lo ejecute, el arte se asienta en la parte superior de la ventana. Por ejemplo, así.
¿Cómo puedo arreglar esto? ¿Hay alguna manera de hacer que vaya hacia la izquierda o hacia la derecha cuando llegue a uno de los cuatro bordes?
¡Tu random_number_for_walking
es incorrecto!
Su función de paso tiene 4
caminos:
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 } // ... }
Pero su random_number_for_walking
es 5 y random(number)
le da un número entre [0, number)
, entonces en su caso: 0, 1, 2, 3, 4
.
Y si miras else
de cerca, no manejas la choice == 3
, con eso en realidad estás manejando la choice == 3 || choice == 4
.
Esto hace que sea más probable que su Walker
se mueva hacia arriba que hacia abajo.
Manejar correctamente la última opción y reducir random_number_for_walking
a 4
resolverá el problema.