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

Processing中基于鼠标输入实现星形原地旋转的问题求助

解决原地旋转问题的核心方案

Processing中实现原地旋转的关键是遵循正确的坐标系变换顺序,同时调整图形的绘制坐标为相对旋转中心的偏移量。以下是具体解决步骤和修改后的代码:

核心逻辑说明

  1. 先通过translate()将坐标系原点移动到旋转中心(你的案例中是(900,500))
  2. 再使用rotate()对坐标系进行旋转
  3. 绘制图形时,将所有绝对坐标转换为相对旋转中心的偏移量
  4. 用pushMatrix()和popMatrix()隔离不同图形的变换,避免互相干扰

修改后的完整代码

float centerX = 900;
float centerY = 500;
float rotateAngle1 = 0; // 第一个星形的顺时针旋转角度
float rotateAngle2 = 0; // 第二个星形的逆时针旋转角度
float prevMouseX, prevMouseY;

void setup(){
  size (1800,1000);
}

void mousePressed() {
  // 记录鼠标按下时的初始位置
  prevMouseX = mouseX;
  prevMouseY = mouseY;
}

void mouseDragged() {
  // 计算鼠标相对于旋转中心的角度变化
  float prevAngle = atan2(prevMouseY - centerY, prevMouseX - centerX);
  float currAngle = atan2(mouseY - centerY, mouseX - centerX);
  float angleDiff = currAngle - prevAngle;
  
  // 更新两个星形的旋转角度
  rotateAngle1 += angleDiff;
  rotateAngle2 -= angleDiff;
  
  // 更新鼠标前一帧位置
  prevMouseX = mouseX;
  prevMouseY = mouseY;
}

void draw() {
  background (0);
  
  // 绘制第一个星形(顺时针旋转)
  pushMatrix();
  translate(centerX, centerY);
  rotate(rotateAngle1);
  drawStar1();
  popMatrix();
  
  // 绘制第二个星形(逆时针旋转)
  pushMatrix();
  translate(centerX, centerY);
  rotate(rotateAngle2);
  drawStar2();
  popMatrix();
  
  // 绘制中心黑色遮罩圆
  fill(0,0,0);
  circle(centerX, centerY, 425);
}

// 第一个星形:所有坐标转换为相对旋转中心的偏移量
void drawStar1() {
  beginShape();
  fill(139,19,191);
  triangle(100,100,0,350,-100,100);
  fill(20,134,245);
  triangle (200,-100,350,100,100,100);
  fill(191,8,8);
  triangle(-100,100,-350,100,-200,-100);
  fill(86,165,3);
  triangle(-200,-100,-350,-400,0,-150);
  fill(167,167,166);
  triangle(0,-150,350,-400,200,-100);
  endShape();
}

// 第二个星形:同样转换为相对旋转中心的偏移量
void drawStar2() {
  beginShape();
  fill(139,19,191);
  triangle(-100,-150,0,-400,100,-150);
  fill(86,165,3);
  triangle(100,-150,350,-150,200,50);
  fill(167,167,166);
  triangle(-200,50,-350,-150,-100,-150);
  fill(20,134,245);
  triangle(-200,50,-350,350,0,150);
  fill(191,8,8);
  triangle(200,50,350,350,0,150);
  endShape();
}

关键细节解释

  • 坐标转换:将原代码中的绝对坐标(如1000,600)减去旋转中心坐标(900,500),得到相对偏移量(如100,100),确保图形围绕中心绘制。
  • 矩阵隔离:pushMatrix()保存当前坐标系状态,popMatrix()恢复原状态,避免多个图形的变换互相影响。
  • 鼠标拖拽控制:通过atan2()计算鼠标相对于中心的角度差,直接映射为星形的旋转角度,实现拖拽时的跟随旋转效果。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.09 20:25:13