以下是我的代码。我试图使中心球体围绕其轨道旋转一部分,然后当它击中其轨道(-orbitRadius, 0)
上的点时,它只是移动到左侧。我使用了if语句,但它无法正常工作。问题是我需要以某种方式使代码这样,一旦调用if语句,坐标将使用if循环中的版本而不是原始公式计算。它只能按原样执行一帧。有人可以帮忙吗?
import java.util.*;
import java.awt.*;
public class Spiral
{
public static void main(String[] args)
{
int rcircle = 200;
int radius = 0;
escape(rcircle, radius);
}
public static void escape (int rcircle, int radius)
{
StdDraw.setCanvasSize(600, 400);
StdDraw.setXscale(0, 600);
StdDraw.setYscale(0, 400);
double xprof;
double yprof;
long T0 = System.currentTimeMillis();
final int FRAME_TIME = 50;
for (int t = 0; t<= 1000; t++) { // note: Prof. Yang starts in his optimal position
double x = (Math.cos(Math.toRadians(0+(3)*4)*t)*rcircle/12 + 300);
double y = (Math.sin(Math.toRadians(0+(3)*4)*t)*rcircle/12 + 200);
if (y == 0) {
x = (300 - rcircle/12) - 12*t;
y = 0;
}
StdDraw.circle(x, y, 10);
xprof = (Math.cos(Math.toRadians(0+4*t))*rcircle + 300);
yprof = (Math.sin(Math.toRadians(0+4*t))*rcircle + 200);
StdDraw.filledCircle(xprof, yprof, 10);
StdDraw.show(FRAME_TIME);
StdDraw.clear();
}
}
}
答案 0 :(得分:1)
你有很多问题:
y的偏移量为200,因此y永远不会为零
很可能会出现一些舍入错误,因此检查200并不是更好。尝试类似:
if(Math.abs(y-200)&lt; 0.0001)
您的代码不会让球体继续向左移动,因为y将在下一轮循环时重新计算。一旦
球体从(orbitRadius, 200)
开始,所以如果你固定点3,球体将向左移动(y == 200)
以下是1-3固定的解决方案:
import java.util.*;
import java.awt.*;
public class Spiral
{
public static void main(String[] args)
{
int rcircle = 200;
int radius = 0;
escape(rcircle, radius);
}
public static void escape (int rcircle, int radius)
{
StdDraw.setCanvasSize(600, 400);
StdDraw.setXscale(0, 600);
StdDraw.setYscale(0, 400);
double xprof;
double yprof;
long T0 = System.currentTimeMillis();
final int FRAME_TIME = 50;
double y = 0;
for (int t = 0; t<= 1000; t++) { // note: Prof. Yang starts in his optimal position
double x = (Math.cos(Math.toRadians(0+(3)*4)*t)*rcircle/12 + 300);
if (Math.abs(y-200) < 0.0001) {
x = (300 - rcircle/12) - 12*t;
y = 200;
} else {
y = (Math.sin(Math.toRadians(0+(3)*4)*t)*rcircle/12 + 200);
}
StdDraw.circle(x, y, 10);
xprof = (Math.cos(Math.toRadians(0+4*t))*rcircle + 300);
yprof = (Math.sin(Math.toRadians(0+4*t))*rcircle + 200);
StdDraw.filledCircle(xprof, yprof, 10);
StdDraw.show(FRAME_TIME);
StdDraw.clear();
}
}
}