繁体   English   中英

P5.JS 随机游走总是在顶部边界结束

[英]P5.JS Random Walk Always Ends Up On the Top Border

我正在通过“代码的本质”学习 P5.JS,并尝试第一个示例代码。

https://github.com/nature-of-code/noc-examples-p5.js/tree/master/chp00_introduction/NOC_I_01_RandomWalkTraditional

 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>

但是,无论我运行多少次,艺术都停留在window的顶部。例如,像这样。

P5.JS 随机游走图像

我怎样才能解决这个问题? 当它碰到四个边界之一时,有没有办法让它 go 向左或向右?

你的random_number_for_walking是错误的!

您的步骤 function 有4条路径:

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
    }

    // ...
}

但是你的random_number_for_walking是 5 并且random(number)给你一个介于[0, number)之间的数字,所以在你的情况下: 0, 1, 2, 3, 4

如果你仔细观察,你不会处理choice == 3else你实际上正在处理choice == 3 || choice == 4 choice == 3 || choice == 4

这使得您的Walker更有可能向上移动而不是向下移动。

正确处理最后的选择并将random_number_for_walking减少到4将解决问题。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM