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

基于createGraphics和for循环实现随机小球瓦片动画,如何让各瓦片小球初始位置不同?

解决瓦片动画中每个小球初始位置不同的问题

问题描述

我正使用createGraphics与for循环制作瓦片动画,当前各瓦片中的随机小球初始位置一致,请问如何实现每个瓦片中的随机小球从不同位置启动?

原尝试代码

let graphics;
let x;
let y;

function setup() {
  createCanvas(400, 400);
  pixelDensity(1);
  graphics=createGraphics(200,200);
  graphics.background(255,0,0);
  x=graphics.width/2;
  y=graphics.height/2;
}

function draw() {
  background(220);
  
  for ( let i=0; i<width; i+=200){
    for ( let j=0; j<height; j+=200){
      image(graphics,i,j);  
      graphics.fill(0);
      graphics.strokeWeight(2);
      graphics.stroke(255,0,0);
      graphics.ellipse(x+i,y+j,10);
      
      x+=random(-5,5);
      y+=random(-5,5);
  
      if ( x<0 || x > graphics.width){
        x=graphics.width/2;
      }
  
      if ( y<0 || y > graphics.height){
        y=graphics.height/2;
      }  
    }
  }  
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.9.0/p5.js"></script>

问题分析

核心问题是全局变量x、y被所有瓦片共用,所有瓦片的小球都基于这两个变量绘制和更新,导致初始位置完全一致,运动也同步。要实现独立运动,必须为每个瓦片单独存储位置数据。

修改后的代码

let graphics;
// 存储每个瓦片的小球位置,每个元素包含独立的x、y坐标
let ballPositions = [];

function setup() {
  createCanvas(400, 400);
  pixelDensity(1);
  graphics = createGraphics(200, 200);
  graphics.background(255, 0, 0);
  
  // 计算瓦片总数,为每个瓦片生成随机初始位置
  const tileCountX = width / 200;
  const tileCountY = height / 200;
  for (let i = 0; i < tileCountX; i++) {
    for (let j = 0; j < tileCountY; j++) {
      ballPositions.push({
        x: random(graphics.width),
        y: random(graphics.height)
      });
    }
  }
}

function draw() {
  background(220);
  
  let index = 0;
  for (let i = 0; i < width; i += 200) {
    for (let j = 0; j < height; j += 200) {
      // 重置graphics背景,清除上一帧的小球痕迹
      graphics.background(255, 0, 0);
      // 获取当前瓦片对应的小球位置
      const pos = ballPositions[index];
      
      // 在graphics画布上绘制小球
      graphics.fill(0);
      graphics.strokeWeight(2);
      graphics.stroke(255, 0, 0);
      graphics.ellipse(pos.x, pos.y, 10);
      
      // 更新当前小球的位置
      pos.x += random(-5, 5);
      pos.y += random(-5, 5);
      
      // 边界检测,超出范围后重置到中心
      if (pos.x < 0 || pos.x > graphics.width) {
        pos.x = graphics.width / 2;
      }
      if (pos.y < 0 || pos.y > graphics.height) {
        pos.y = graphics.height / 2;
      }
      
      // 将绘制好的瓦片放到画布对应位置
      image(graphics, i, j);
      index++;
    }
  }
}

关键修改说明

  • 用ballPositions数组替代全局变量,每个元素对应一个瓦片的小球初始随机位置,确保启动时位置不同
  • 每次绘制瓦片前重置graphics的背景,避免上一帧的小球残留到当前帧
  • 遍历瓦片时通过index关联到数组中对应的位置数据,实现每个小球独立更新运动

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.01 02:56:23