我有一个用java制作的简单游戏动画。它由三个围绕轴旋转的行星组成。每个行星都是该类的一个实例,Planet
它们有一个更新方法,每次运行时,轨道的旋转角度都会增加,并且位置会根据角度和一些预定变量(例如与“太阳”的距离)进行更新。从这里,您可以用简单的三角法确定行星的位置。在这种情况下:
Sin(angle) = op/hyp = y/distance
therefore
Sin(angle)*hyp = op
Cos(angle) = ady/hyp = x/distance
therefore
Cos(angle)*hyp = ady
其中,斜边是到太阳的距离,邻边和对边分别是 x 和 y 值。我认为这会起作用,直到我尝试过。它给了我一个椭圆的旋转。这是更新行星自转的代码(轨道中心是太阳的中心位置):
position.x = ((Math.cos(orbitAngle) * orbitDistance) + orbitCenter.x);
position.y = ((Math.sin(orbitAngle) * orbitDistance) + orbitCenter.y);
有什么问题?
编辑:
我通过将一个物体的中心放置在轨道中心指定的位置来实现这个问题
这是行星类的完整代码:
public class Planet
{
protected Image image;
protected Vector2 position;
protected final Vector2 orbitCenter;
protected float rotation;
protected Vector2 imageSize;
protected final float rotationSpeed;
protected final float orbitDistance;
protected float orbitAngle;
protected final float orbitAngleSpeed;
public Planet(Image image, float orbitDistance, float rotationSpeed, Vector2 orbitCenter, float orbitAngleSpeed)
{
this.image = image;
this.position = new Vector2(orbitCenter.x, orbitCenter.y - orbitDistance);
this.orbitCenter = orbitCenter;
this.rotation = 0;
this.imageSize = new Vector2(image.getWidth(null), image.getHeight(null));
this.rotationSpeed = rotationSpeed;
this.orbitDistance = orbitDistance;
this.isMouseOver = false;
this.isPressed = false;
this.orbitAngle = 0;
this.orbitAngleSpeed = orbitAngleSpeed;
}
public void Update()
{
orbitAngle += orbitAngleSpeed;
if(orbitAngle > Math.PI * 2)
orbitAngle %= Math.PI * 2;
position.x = ((Math.cos(orbitAngle) * orbitDistance) + orbitCenter.x);
position.y = ((Math.sin(orbitAngle) * orbitDistance) + orbitCenter.y);
}
public void Draw(Graphics2D g)
{
g.rotate(rotation, position.x + imageSize.x / 2, position.y + imageSize.y / 2);
g.drawImage(image, (int)position.x, (int)position.y, null);
g.rotate(-rotation, position.x + imageSize.x / 2, position.y + imageSize.y / 2);
}
}
这是测试行星类的类。你可以从这里下载它需要工作的 jar:foxtailgames.net/AppletSource.jar。这是测试器类(您可能必须导入一些东西,但如果您在 eclipse 或 netbeans 中执行它,它会给您导入):
public class PlanetTest extends AppletCore
{
public void resizeScreen() {resize(800, 800);}
Image center;
Planet p;
public void LoadContent()
{
p = new Planet(loadImage("images/GameMenuCircles/Planet1.png"), 100f, 0.02f, new Vector2(400, 400), 0.005f);
center = loadImage("images/GameMenuCircles/Center.png");
}
public void Update(GameTime gameTime)
{
p.Update();
}
public void Draw(Graphics2D g, GameTime gameTime)
{
g.drawImage(center, 400 - center.getWidth(null)/2, 400 - center.getWidth(null)/2, null);
p.Draw(g);
g.setColor(Color.green);
g.drawLine(400, 400, 500, 400);
g.drawLine(400, 400, 400, 500);
g.drawLine(400, 400, 300, 400);
g.drawLine(400, 400, 400, 300);
g.setColor(Color.white);
}
}