如何在Java中使一个对象围绕另一个移动对象旋转?

2022-07-25 00:00:00 rotation affinetransform java

我对Java非常陌生,我想编写一个简单的太阳系统,在这个系统中,月球绕地球公转,地球绕太阳公转。 一切都很正常,除了月球不想正确移动:/ 由于地球偏离月球的初始位置,月球的自转半径也相应增大。同样,当地球更接近月球的惯性位置时,自转半径也会减小。 如果初始位置为(0;0),则它起作用,但月球撞击太阳...

那么我如何才能保持地球和月球之间的距离恒定呢? 我正在使用AffineTransform,以下是我的代码片段;)

提前谢谢!

Ellipse2D.Double MoonFrame = new Ellipse2D.Double(orbitEarth + orbitMoon - radiusMoon, -radiusMoon, radiusMoon*2, radiusMoon*2);

for (int i = 0; i < 360; i++)
  {
    theta += Math.PI/30;
    AffineTransform TransformMoon = AffineTransform.getRotateInstance(theta,TransformEarth.getTranslateX(),TransformEarth.getTranslateY());

    g2d.fill(TransformMond.createTransformedShape(MoonFrame));
  }

解决方案

因此,您的基本问题可以归结为"如何找到给定角度的圆上的点"...说真的,就这么简单

基于多个小时的谷歌搜索和反复试验,我基本上使用了以下内容,或多或少。

protected Point pointOnCircle() {

    double rads = Math.toRadians(orbitAngle - 180); // Make 0 point out to the right...
    int fullLength = Math.round((outterRadius));

    // Calculate the outter point of the line
    int xPosy = Math.round((float) (Math.cos(rads) * fullLength));
    int yPosy = Math.round((float) (Math.sin(rads) * fullLength));

    return new Point(xPosy, yPosy);
}

剩下的基本上归结为正确处理转换的复合性质,

基本上,这将获取一个基本Graphics上下文,将平移应用到它(地球的位置),并创建另外两个上下文以应用其他变换,一个用于地球,一个用于月球...

Graphics2D g2d = (Graphics2D) g.create();
int yPos = (getHeight() - size) / 2;
// Transform the offset
g2d.transform(AffineTransform.getTranslateInstance(xPos, yPos));

Graphics2D earthG = (Graphics2D) g2d.create();
// Rotate around the 0x0 point, this becomes the center point
earthG.transform(AffineTransform.getRotateInstance(Math.toRadians(angle)));
// Draw the "earth" around the center point
earthG.drawRect(-(size / 2), -(size / 2), size, size);
earthG.dispose();

// Removes the last transformation
Graphics2D moonG = (Graphics2D) g2d.create();            
// Calclate the point on the circle - based on the outterRadius or
// distance from the center point of the earth
Point poc = pointOnCircle();
int moonSize = size / 2;
// This is only a visial guide used to show the position of the earth
//moonG.drawOval(-outterRadius, -outterRadius, outterRadius * 2, outterRadius * 2);
moonG.fillOval(poc.x - (moonSize / 2), poc.y - (moonSize / 2), moonSize, moonSize);
moonG.dispose();

g2d.dispose();

因为我知道这会让你抓狂,这是一个可行的例子...

import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.geom.AffineTransform;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import javax.swing.Timer;

public class Test {

    public static void main(String[] args) {
        new Test();
    }

    public Test() {
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                JFrame frame = new JFrame();
                frame.add(new TestPane());
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
    }

    public class TestPane extends JPanel {

        private double angle;
        private double orbitAngle;
        private int xPos = 0;
        private int size = 20;
        private int outterRadius = size * 2;
        private int delta = 2;

        public TestPane() {
            new Timer(40, new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    xPos += delta;
                    if (xPos + size >= getWidth()) {
                        xPos = getWidth() - size;
                        delta *= -1;
                    } else if (xPos < 0) {
                        xPos = 0;
                        delta *= -1;
                    }
                    angle += 4;
                    orbitAngle -= 2;
                    repaint();
                }
            }).start();
        }

        @Override
        public Dimension getPreferredSize() {
            return new Dimension(400, 200);
        }

        protected Point pointOnCircle() {

            double rads = Math.toRadians(orbitAngle - 180); // Make 0 point out to the right...
            int fullLength = Math.round((outterRadius));

            // Calculate the outter point of the line
            int xPosy = Math.round((float) (Math.cos(rads) * fullLength));
            int yPosy = Math.round((float) (Math.sin(rads) * fullLength));

            return new Point(xPosy, yPosy);
        }

        @Override
        protected void paintComponent(Graphics g) {
            super.paintComponent(g);
            Graphics2D g2d = (Graphics2D) g.create();
            int yPos = (getHeight() - size) / 2;
            // Transform the offset
            g2d.transform(AffineTransform.getTranslateInstance(xPos, yPos));

            Graphics2D earthG = (Graphics2D) g2d.create();
            // Rotate around the 0x0 point, this becomes the center point
            earthG.transform(AffineTransform.getRotateInstance(Math.toRadians(angle)));
            // Draw the "earth" around the center point
            earthG.drawRect(-(size / 2), -(size / 2), size, size);
            earthG.dispose();

            // Removes the last transformation
            Graphics2D moonG = (Graphics2D) g2d.create();            
            // Calclate the point on the circle - based on the outterRadius or
            // distance from the center point of the earth
            Point poc = pointOnCircle();
            int moonSize = size / 2;
            // This is only a visial guide used to show the position of the earth
            //moonG.drawOval(-outterRadius, -outterRadius, outterRadius * 2, outterRadius * 2);
            moonG.fillOval(poc.x - (moonSize / 2), poc.y - (moonSize / 2), moonSize, moonSize);
            moonG.dispose();

            g2d.dispose();
        }

    }

}

这会使"地球"物体朝一个方向旋转,然后使月球绕其旋转,朝相反的方向旋转

相关文章