Java 处理中:使用鼠标围绕一个点旋转

Java Processing: Rotate about a Point Using the Mouse

我正在创建一个 java 处理程序,其中我需要在按住鼠标时围绕一个点旋转一个矩形。

一些限制:

  1. 只能旋转180度(半圆)
  2. 一旦到达 180 度的终点,它必须反转其旋转方向。

如有任何帮助,我们将不胜感激。附上我的程序。

void setup() {
    size(600, 600);
    smooth();
}

void draw() {
    background(0);
    noStroke();
    fill(169,169,169); 

    translate(width/2, height/2);

    boolean run=true;
    if (mousePressed==true && run==true){
        rotate(radians(frameCount/2));
    }
    if (mousePressed==false){
        run=false;
    }
    if(mousePressed==true  && run==false){
        run=true;
    }
    fill(255);
    rect(-50, -50, 50, 50);
}

rect的第3个和第4个参数不是矩形的右下角点,而是它的宽和高
如果执行旋转 (rotate()),则对象将围绕其中心旋转。

您必须定义一个矩形,中心点为 (0, 0)。例如:

rect(-50, -50, 50, 50);

rect(-25, -25, 50, 50);

如果你想围绕一个轴旋转一个对象(poivot_xpoivot_y),那么你必须:

  • 以这种方式平移对象,即枢轴位于 (0, 0):translate(-poivot_x, -poivot_y)

  • 然后旋转对象:rotate(...)

  • 最后将枢轴平移回原来的位置:translate(poivot_x, poivot_y)

由于像rotate()scale()translate()这样的矩阵运算,定义一个矩阵并将当前矩阵乘以新矩阵,此操作必须以相反的顺序进行。

例如围绕上边 (25, 0) 的中心旋转矩形 (0, 0, 50, 50):

int poivot_x = 25; // center
int poivot_y = 0;  // top

translate(poivot_x, poivot_y);
rotate(radians(frameCount/2));
translate(-poivot_x, -poivot_y);

rect(0, 0, 50, 50);