为何20个MovingMark对象同步旋转?代码调试求助
问题排查与修复
核心问题
所有MovingMark实例同步旋转的原因是默认构造函数未初始化theta变量:
- 类中
theta变量未赋初始值,所有实例创建时theta默认是0 - 每个对象的
move()方法都对theta加0.01,初始值相同导致旋转进度完全同步
修复步骤
在MovingMark的默认构造函数中,给theta添加随机初始角度赋值,让每个对象从不同的旋转状态开始:
MovingMark() { x = random(width); y = random(height); r = random(1); c = random(255); a = random(255); b = random(255); theta = random(TWO_PI); // 添加这行,赋予随机初始旋转角度 }
额外优化建议
你的代码中设置了colorMode(HSB, 360, 100, 100),但构造函数里给色相(a)、饱和度(b)、亮度(c)赋值用的是random(255),超出了HSB模式的取值范围,会导致颜色显示异常,建议修改为对应范围:
a = random(360); // 色相范围0-360 b = random(100); // 饱和度范围0-100 c = random(100); // 亮度范围0-100
修改后的完整代码
MovingMark[] mks = new MovingMark[20]; void setup(){ size(800,600); smooth(); colorMode(HSB, 360, 100, 100); for(int i=0; i<mks.length; i++) mks[i] = new MovingMark(); } void draw() { background(255); ellipseMode(CENTER); for(int i=0; i<mks.length; i++) { mks[i].draw(); mks[i].move(); } } class MovingMark { float x=150, y=150, r=1, a=0,b=0,c=0,theta; MovingMark() { x = random(width); y = random(height); r = random(1); a = random(360); b = random(100); c = random(100); theta = random(TWO_PI); // 随机初始角度 } MovingMark(float x, float y, float r,float c,float theta,float a,float b) { this.x = x; this.y = y; this.r = r; this.c = c; this.theta = theta; this.a = a; this.b = b; } void draw() { pushMatrix(); translate(x, y); rotate(theta); fill(a,b,c); ellipse(150, 150,150, 150); //white fill(255); ellipse(150,150,45,45); //line noFill(); stroke(255); strokeWeight(2); arc(150,150,70,70,radians(280),radians(350)); popMatrix(); } void move() { theta += 0.01; } }
内容的提问来源于stack exchange,提问作者user24326547
相关产品推荐
相关产品推荐

