我想在java处理中以圆周运动移动一个正方形



这是一个学校项目,所以我不能使用很多功能,如翻译或旋转。我得用基本的三角函数来做这个。我做了一个正方形,我需要它做360度的圆周运动,其中一个点保持不变。

float rotX,rotY;
size(500,500);
fill(#B71143);
int rectX=width/4;
int rectY=height/10;
int rectSize=30;
angle=angle+0.1;
//rotX=rectX*cos(angle)-rectY*sin(angle);
//rotY=rectX*cos(angle)+rectY*sin(angle);
square(rotX,rotY,rectSize);

你很接近了,至少在三角函数部分。

在处理方面,您只缺少setup()draw(),它们将绘制单个帧(一旦您取消注释rotX, rotY的赋值并将angle初始化为0)

下面是应用了上述注释的代码:
float rotX, rotY;
float angle = 0;
void setup() {
size(500, 500);
fill(#B71143);
}
void draw() {
int rectX=width/4;
int rectY=height/10;
int rectSize=30;
angle=angle+0.1;

rotX = rectX*cos(angle)-rectY*sin(angle);
rotY = rectX*cos(angle)+rectY*sin(angle);


square(rotX, rotY, rectSize);
}

另外,如果你想从中心绘制,你可以在渲染前为正方形坐标添加一半的宽度/高度(相当于转换到中心),如果你想画一个圆而不是椭圆形,为两个半径使用相同的大小(命名为rectX, rectY):

float rotX, rotY;
float angle = 0;
void setup() {
size(500, 500);
fill(#B71143);
rectMode(CENTER);
}
void draw() {
int rectX=width/4;
int rectY=height/4;
int rectSize=30;
angle=angle+0.1;

rotX = rectX*cos(angle)-rectY*sin(angle);
rotY = rectX*cos(angle)+rectY*sin(angle);

// offset to center
rotX += width / 2;
rotY += height / 2;

square(rotX, rotY, rectSize);
}

我个人会简化一些代码(尽管你的作业要求可能会根据你的课程而有所不同)。

// initialise angle value
float angle = 0;
void setup() {
size(500, 500);
fill(#B71143);
}
void draw() {
// circular motion radius
int radius = width / 4;
// define square size
int rectSize=30;
// increment the angle (rotating around center)
angle=angle+0.1;
// convert polar (angle, radius) to cartesian(x,y) coords
float x = cos(angle) * radius;
float y = sin(angle) * radius;

// offset to center
x += width / 2;
y += height / 2;
// render the square at the rotated position
square(x, y, rectSize);
}

(如果你想了解另一个极坐标到笛卡尔坐标的转换公式,你可以在这里查看我以前的答案,其中包括一个交互式演示)

最新更新