You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

P5.JS传统随机游走示例运行后总停留在顶部边框如何修复

问题根因

你代码里的随机方向逻辑存在概率偏差问题:

  • 你定义了random_number_for_walking = 5,floor(random(5))会生成0、1、2、3、4共5个随机整数
  • 但分支判断仅覆盖了0-3四个值,choice=4的场景会进入最后一个else分支,也就是执行向上移动(y坐标减)的逻辑
  • 这就导致向上走的概率是2/5,其余三个方向各占1/5,长期运行游走点必然会慢慢漂移到顶部边界,后续再触发向上指令时,constrain方法会固定y值,就会出现卡住不动的情况
修复方案
  1. 首先修正方向概率:将random_number_for_walking改为4,保证四个方向移动概率均等
  2. 新增边界碰撞逻辑:判断游走点当前是否处在边界,若碰到上下边界则仅允许左右移动,若碰到左右边界则仅允许上下移动,避免卡住
完整修改后代码

JS代码

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;

// 修改为4,保证四个方向概率均等
let random_number_for_walking = 4;

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() {
    let choice;
    // 判断是否在上下边界
    const isOnTopBorder = this.y <= 0;
    const isOnBottomBorder = this.y >= height - stroke_weight;
    // 判断是否在左右边界
    const isOnLeftBorder = this.x <= 0;
    const isOnRightBorder = this.x >= width - stroke_weight;

    if (isOnTopBorder || isOnBottomBorder) {
      // 碰到上下边界,仅允许左右移动
      choice = floor(random(2));
      if (choice === 0) {
        this.x += stroke_weight;
      } else {
        this.x -= stroke_weight;
      }
    } else if (isOnLeftBorder || isOnRightBorder) {
      // 碰到左右边界,仅允许上下移动
      choice = floor(random(2));
      if (choice === 0) {
        this.y += stroke_weight;
      } else {
        this.y -= stroke_weight;
      }
    } else {
      // 不在边界,正常四方向随机
      choice = floor(random(random_number_for_walking));
      if (choice === 0) {
        this.x += stroke_weight;
      } else if (choice == 1) {
        this.x -= stroke_weight;      
      } else if (choice == 2) {
        this.y += stroke_weight;      
      } else {
        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);
}

HTML代码

<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.4.0/p5.min.js"></script>

内容的提问来源于stack exchange,提问作者Jay

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.02 02:57:00