我获得了一个processing.js示例,说明如何在gamedev.stackexchange here上由用户围绕另一个对象进行轨道运行。
基本上,在该示例中,原点或中心与轨道点的共同点一起建立:
// Logic vars
PVector origin;
float orbitRadius = 75.0;
PVector orbitVelocity;
PVector orbitPoint;
float t = 0.0;
float fps = 60.0;
float constDT = 1 / fps;
然后,它们在设置中初始化:
void setup() {
size(400, 400);
frameRate(fps);
/*central point */
origin = new PVector(width / 2.0, height / 2.0);
/*first point and velocity of orb around center*/
orbitVelocity = new PVector(0.0, /*-orbitRadius*/orbitRadius);
orbitPoint = new PVector(origin.x + orbitRadius, origin.y);
}
然后每一步都更新轨道点的共同点:
void update(float dt) {
/*update orbit of first orb using velocity*/
PVector accelerationTowardsOrigin = PVector.sub(origin, orbitPoint);
orbitVelocity.add(PVector.mult(accelerationTowardsOrigin, /*dt*/constDT));
orbitPoint.add(PVector.mult(orbitVelocity, /*dt*/constDT));
}
(我已经省略了绘图代码,因为它不相关。)我一直在尝试更新代码以添加其他轨道椭圆,可以看到here。我已经能够通过添加这些附加变量
成功地在中心点周围的轨道上添加第二个点/*Logic vars for second point on circle*/
PVector orbitPoint2;
PVector orbitVelocity2;
float circAngle;
float xcoord_along_circle;
float ycoord_along_circle;
并将其添加到设置:
//Added in setup
/*second orbiting point for second orb*/
/*Calculate second point along circle*/
circAngle = 90.0;
xcoord_along_circle = orbitRadius * cos(circAngle) + origin.x;
ycoord_along_circle = orbitRadius * sin(circAngle) + origin.y;
/*second point and velocity of orb around center*/
orbitVelocity2 = new PVector(xcoord_along_circle,orbitRadius);
orbitPoint2 = new PVector(xcoord_along_circle, ycoord_along_circle);
然而,当我更新第二个椭圆的共同点时,每个点都会产生一个伸展的细长轨道:
/*update orbit of second orb using velocity*/
PVector accelerationTowardsOrigin2 = PVector.sub(origin,orbitPoint2);
orbitVelocity2.add(PVector.mult(accelerationTowardsOrigin2,/*dt*/constDT));
orbitPoint2.add(PVector.mult(orbitVelocity2, /*dt*/constDT));
我相信我正在做正确的事情,并复制必要的步骤。我怎样才能纠正这个问题,以免轨道扭曲?
答案 0 :(得分:1)
此时,您在整个地方复制代码,而不是通过捕获类中的轨道体来模块化您的代码,您可以简单地构建一百万次。我建议先将代码重写为
class OrbitalBody {
float ox, oy, x, y, m, a;
OrbitalBody(float originX, float originY, float startX, float startY, float mass, float speed) {
ox = originX;
oy = originY;
x = startX;
y = startY;
m = mass;
a = speed / 200;
}
void update() {
float nx = (x-ox) * cos(a) - (y-oy) * sin(a),
ny = (x-ox) * sin(a) + (y-oy) * cos(a);
x = nx+ox;
y = ny+oy;
}
void draw() {
fill(255);
ellipse(x,y,m,m);
}
}
ArrayList<OrbitalBody> bodies = new ArrayList<OrbitalBody>();
int mx, my;
void setup() {
size(420, 420);
mx = width/2;
my = height/2;
bodies.add(new OrbitalBody(mx, my, mx-50, my, 10, 10));
bodies.add(new OrbitalBody(mx, my, mx-100, my, 20, 3));
bodies.add(new OrbitalBody(mx, my, mx-120, my, 5, 13));
bodies.add(new OrbitalBody(mx, my, mx-170, my, 15, 6));
bodies.add(new OrbitalBody(mx, my, mx-190, my, 10, 9));
ellipseMode(CENTER);
}
void draw() {
background(0);
fill(100,100,0);
ellipse(mx,my,50,50);
for(OrbitalBody b: bodies) {
b.update();
b.draw();
}
}