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

P5.js技术求助:表情符号无法沿圆周移动问题排查

问题:表情符号沿圆周移动异常分析

我正在实现让表情符号沿圆周移动的功能:移除background()调用时,表情会绘制出完整的圆周轨迹;保留该函数调用时,表情仅随机出现在圆周的某个位置且无法移动。请问我忽略了什么?

相关代码

let rndnmbr;
let dataArr;
let ship1;
let ship2;
let cxy = 500;
let circlegaps = 250;
function setup() {
  angleMode(DEGREES)
  createCanvas(1000, 1000);
  background(220);
  noFill();
  ship1 = '⛴';
  ship2 = '⛵';
  // Daten hier eintragen, getrennt durch Komma:
  dataArr = [125,250,375,500]; 
  
  let colorArr = ['red','blue','green','yellow'];
  
  rndnmbr = [int(random(0,180)),int(random(0,180)),int(random(0,180)),int(random(0,180))];
  /*
  for(let i=0;i<dataArr.length;i++){
    fill('black');
    let rAng1 = random(0,90);
    let rAng2 = 180;
    text(shlong, (int(dataArr[i]*cos(rAng2)))+500,(int(dataArr[i]*sin(rAng2)))+500);
    
    //circle((int(dataArr[i]*cos(rAng1)))+500,(int(dataArr[i]*sin(rAng1)))+500,10);
   */
  }


function draw() {
  
    for(let j=0;j<360;j++){
      noFill();
    
      background(230);
      circle(cxy,cxy,circlegaps);
      circle(cxy,cxy,circlegaps*2);
      circle(cxy,cxy,circlegaps*3);
      circle(cxy,cxy,circlegaps*4);

      for(let i=0;i<dataArr.length;i++){
      fill('black');
      let rAng2 = j+rndnmbr[i];  
      print(rAng2);
        text(ship1, (int(dataArr[i]*cos(rAng2)))+cxy,(int(dataArr[i]*sin(rAng2)))+cxy);
      } 
    }
}

问题原因

核心问题出在draw()函数内部的for(let j=0;j<360;j++)循环:

  • draw()函数本身会以默认帧率(通常60帧/秒)持续执行,每次执行都会从头跑一遍内部代码。
  • 你在draw()里加了一个0到359的循环,这会在单帧内把j从0直接跑到359,瞬间计算出表情在圆周所有位置的坐标,最后只显示j=359时的位置,看起来就像表情固定在某个随机点。
  • 当你去掉background()时,每帧循环里绘制的所有位置不会被清除,所以会留下完整的圆周轨迹。

修复方案

  1. 把j变量提到全局作用域,作为帧计数器使用,不要在draw()里写0到359的循环
  2. 每次draw()执行时,让j递增(超过360后重置为0),这样每帧只绘制表情当前的位置,实现平滑移动

修改后的代码示例

let rndnmbr;
let dataArr;
let ship1;
let ship2;
let cxy = 500;
let circlegaps = 250;
let j = 0; // 把j设为全局变量

function setup() {
  angleMode(DEGREES)
  createCanvas(1000, 1000);
  background(220);
  noFill();
  ship1 = '⛴';
  ship2 = '⛵';
  dataArr = [125,250,375,500]; 
  
  rndnmbr = [int(random(0,180)),int(random(0,180)),int(random(0,180)),int(random(0,180))];
}

function draw() {
  background(230);
  circle(cxy,cxy,circlegaps);
  circle(cxy,cxy,circlegaps*2);
  circle(cxy,cxy,circlegaps*3);
  circle(cxy,cxy,circlegaps*4);

  for(let i=0;i<dataArr.length;i++){
    fill('black');
    let rAng2 = j + rndnmbr[i];  
    text(ship1, (int(dataArr[i]*cos(rAng2)))+cxy,(int(dataArr[i]*sin(rAng2)))+cxy);
  } 
  j++;
  if(j > 360) j = 0; // 超过360度重置,避免数值过大
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.07 08:02:39