沿线移动点

时间:2015-01-27 15:28:41

标签: java

我画了一个形状,看起来像字母" Y"。然后我在它底部画了一个小点。

让我们说形状是3行,如下:

the problem

我想沿着第1行,然后是第2行,然后沿着第2行,然后是第3行,最后回到第1行底部的开头。

它以滑块指定的速度移动。

到目前为止,这是我的代码:

public class yyyyy extends JFrame{

private Komponent komponent;
private Timer timer;
private int tick = 0;
private int speed = 4;
private int x1 = 225, y1 = 300, y2 = 225, x3 = 150, y3 = 150, x4 = 300; 
private int x = x1, y = y1;

class Komponent extends JComponent{

    /**
     * 
     */
    private static final long serialVersionUID = -4028514932033769012L;

    @Override
    protected void paintComponent(Graphics arg0) {



        if(tick< y1-y2){
            x = x1;
            y = y1-tick;
        }
        else if(tick>y1-y2 && tick < 2*(y1-y2)){
            x = x1-tick + (y1-y2);
            y = y2-tick + (y1-y2);
        }
        else if(tick>2*(y1-y2) && tick < 3*(y1-y2)){
            x = x3 + tick - 2*(y1-y2);
            y = y3 + tick - 2*(y1-y2);
        }
        else if(tick>3*(y1-y2)&& tick < 4*(y1-y2)){
            x = x1 + tick - 3*(y1-y2);
            y = y2 - tick + 3*(y1-y2);
        }
        else if(tick>4*(y1-y2)&& tick < 5*(y1-y2)){
            x = x4 - tick + 4*(y1-y2);
            y = y3 + tick - 4*(y1-y2);
        }
        else{
            x = x1;
            y = y2 + tick - 5*(y1-y2);
        }
        arg0.setColor(Color.BLUE);
        arg0.drawLine(x1, y1, x1, y2);
        arg0.drawLine(x1,y2,x3,y3);
        arg0.drawLine(x1, y2, x4, y3);

        arg0.setColor(Color.RED);
        arg0.fillOval(x-5, y-5, 10, 10);
        super.paintComponent(arg0);
    }

}
public yyyyy (String string){
    super(string);
    setDefaultCloseOperation(EXIT_ON_CLOSE);
    setBounds(100,100,550,550);
    add(komponent=new Komponent());
    JPanel panel = new JPanel();
    add(panel, BorderLayout.SOUTH);
    final JCheckBox cb = new JCheckBox("Animacja");
    cb.addChangeListener(new ChangeListener() {

        @Override
        public void stateChanged(ChangeEvent e) {
            if(cb.isSelected()){
                timer.start();
            }
            else{
                timer.stop();
            }
        }
    });
    panel.add(cb);
    timer = new Timer(50, new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e) {
            tick+=speed;
            if(tick > 6*(y1 -y2)){
                tick -= 6*(y1-y2);
            }
            if(tick < 0){
                tick = 6*(y2-y1);
            }
            komponent.repaint();
        }
    });

    final JSlider speedSlider = new JSlider(-30,30,speed);
    panel.add(speedSlider);
    speedSlider.addChangeListener(new ChangeListener() {

        @Override
        public void stateChanged(ChangeEvent e) {
            speed = speedSlider.getValue();
            komponent.repaint();
        }
    });
    setLocationRelativeTo(null);
    setVisible(true);
}

public static void main(String[] args){
    EventQueue.invokeLater(new Runnable() {

        @Override
        public void run() {
            new yyyyy("wat");

        }
    });
}

}

现在我有两个问题:  1. tick的重置是否正确定义?我认为它应该在2 *所有线的距离之和后变为0。  2.我用注释标记的代码部分。如何检查点的当前x和y应该是什么?我尝试从线方程中做到这一点,但没有太大的成功(点总是只是在窗外射击)。

编辑:代码更新。

1 个答案:

答案 0 :(得分:2)

虽然评论中已经回答了这个问题(尽管这主要是一个调试提示,虽然这不是一个真正的答案......)我想建议你概括一下。

您应该使用一组固定的坐标手动建模每个线段。相反,你可以创建一个通用的&#34;路径&#34;,应该遵循。路径上的位置可以定义为介于0.0和1.0之间的值。

然后,分离定时和插值,并且可以单独处理定时本身。然后你甚至可以添加漂亮的动画效果,例如,在某处添加一些Math.sin并获得有趣的缓入/缓出效果。

但是,这里有一个MCVE,显示了如何实现这种通用路径跟随器的示例。仅通过更改Y方法中X实例的创建,它可能会从关注PathFollower更改为关注main

import java.awt.BasicStroke;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.Shape;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.geom.Ellipse2D;
import java.awt.geom.Path2D;
import java.awt.geom.Point2D;
import java.util.ArrayList;
import java.util.List;

import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JSlider;
import javax.swing.SwingUtilities;
import javax.swing.Timer;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;

public class PathFollowerTest
{
    public static void main(String[] args)
    {
        final PathFollower pathFollower = createPathFollowerY();
        //final PathFollower pathFollower = createPathFollowerX();

        SwingUtilities.invokeLater(new Runnable()
        {
            @Override
            public void run()
            {
                createAndShowGUI(pathFollower);
            }
        });
    }

    private static PathFollower createPathFollowerY()
    {
        Point2D p0 = new Point2D.Double(225, 300);
        Point2D p1 = new Point2D.Double(225, 225);
        Point2D p2 = new Point2D.Double(150, 150);
        Point2D p3 = new Point2D.Double(300, 150);
        PathFollower pathFollower = new PathFollower();
        pathFollower.addPoint(p0);
        pathFollower.addPoint(p1);
        pathFollower.addPoint(p2);
        pathFollower.addPoint(p1);
        pathFollower.addPoint(p3);
        pathFollower.addPoint(p1);
        pathFollower.addPoint(p0);
        return pathFollower;
    }

    private static PathFollower createPathFollowerX()
    {
        Point2D p0 = new Point2D.Double(150, 300);
        Point2D p1 = new Point2D.Double(225, 225);
        Point2D p2 = new Point2D.Double(150, 150);
        Point2D p3 = new Point2D.Double(300, 300);
        Point2D p4 = new Point2D.Double(300, 150);
        PathFollower pathFollower = new PathFollower();
        pathFollower.addPoint(p0);
        pathFollower.addPoint(p1);
        pathFollower.addPoint(p2);
        pathFollower.addPoint(p1);
        pathFollower.addPoint(p4);
        pathFollower.addPoint(p1);
        pathFollower.addPoint(p3);
        pathFollower.addPoint(p1);
        pathFollower.addPoint(p0);
        return pathFollower;
    }

    private static void createAndShowGUI(final PathFollower pathFollower)
    {
        JFrame f = new JFrame();
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.setBounds(100, 100, 550, 550);
        f.getContentPane().setLayout(new BorderLayout());

        PathFollowerPanel pathFollowerPanel = 
            new PathFollowerPanel(pathFollower);
        f.getContentPane().add(pathFollowerPanel, BorderLayout.CENTER);

        final PathFollowerController pathFollowerController = 
            new PathFollowerController(
                pathFollower, pathFollowerPanel);

        JPanel panel = new JPanel();
        f.getContentPane().add(panel, BorderLayout.SOUTH);
        final JCheckBox cb = new JCheckBox("Animacja");
        cb.addChangeListener(new ChangeListener()
        {
            @Override
            public void stateChanged(ChangeEvent e)
            {
                pathFollowerController.setRunning(cb.isSelected());
            }
        });
        panel.add(cb);

        final JSlider speedSlider = new JSlider(-30, 30, 0);
        panel.add(speedSlider);
        speedSlider.addChangeListener(new ChangeListener()
        {
            @Override
            public void stateChanged(ChangeEvent e)
            {
                pathFollowerController.setSpeed(speedSlider.getValue());
            }
        });
        f.setLocationRelativeTo(null);
        f.setVisible(true);

    }
}

class PathFollowerController
{
    private int speed = 0;
    private PathFollower pathFollower;
    private PathFollowerPanel pathFollowerPanel;

    private final Timer timer = new Timer(50, new ActionListener()
    {
        private double alpha = 0;

        @Override
        public void actionPerformed(ActionEvent e)
        {
            alpha += speed / 500.0;
            alpha %= 1.0;
            while (alpha < -1.0)
            {
                alpha += 1.0;
            }
            pathFollower.setAlpha(alpha < 0 ? -alpha : alpha);
            pathFollowerPanel.repaint();
        }
    });

    PathFollowerController(PathFollower pathFollower,
        PathFollowerPanel pathFollowerPanel)
    {
        this.pathFollower = pathFollower;
        this.pathFollowerPanel = pathFollowerPanel;
    }

    void setRunning(boolean running)
    {
        if (running)
        {
            timer.start();
        }
        else
        {
            timer.stop();
        }
    }

    public void setSpeed(int speed)
    {
        this.speed = speed;
    }
}

class PathFollower
{
    private final List<Point2D> points;
    private Shape path;
    private double pathLength = -1;
    private double alpha = 0;

    PathFollower()
    {
        points = new ArrayList<Point2D>();
    }

    void addPoint(Point2D p)
    {
        points.add(new Point2D.Double(p.getX(), p.getY()));
        path = null;
        pathLength = -1;
    }

    void setAlpha(double alpha)
    {
        this.alpha = alpha;
    }

    Point2D getCurrentPoint()
    {
        return computePoint(alpha);
    }

    Shape getPath()
    {
        if (path == null)
        {
            path = createPath();
        }
        return path;
    }

    private Shape createPath()
    {
        Path2D path = new Path2D.Double();
        for (int i = 0; i < points.size(); i++)
        {
            Point2D p = points.get(i);
            double x = p.getX();
            double y = p.getY();
            if (i == 0)
            {
                path.moveTo(x, y);
            }
            else
            {
                path.lineTo(x, y);
            }
        }
        return path;
    }

    private double computePathLength()
    {
        double pathLength = 0;
        for (int i = 0; i < points.size() - 1; i++)
        {
            Point2D p0 = points.get(i);
            Point2D p1 = points.get(i + 1);
            pathLength += p0.distance(p1);
        }
        return pathLength;
    }

    private Point2D computePoint(double alpha)
    {
        if (pathLength < 0)
        {
            pathLength = computePathLength();
        }
        double alphaPosition = alpha * pathLength;
        double accumulatedLength = 0;
        for (int i = 0; i < points.size() - 1; i++)
        {
            Point2D p0 = points.get(i);
            Point2D p1 = points.get(i + 1);
            double distance = p0.distance(p1);
            double nextLength = accumulatedLength + distance;
            if (nextLength >= alphaPosition)
            {
                double localAlpha = 
                    (alphaPosition - accumulatedLength) / distance;
                double x = p0.getX() + localAlpha * (p1.getX() - p0.getX());
                double y = p0.getY() + localAlpha * (p1.getY() - p0.getY());
                return new Point2D.Double(x, y);
            }
            accumulatedLength = nextLength;
        }
        Point2D p = points.get(points.size() - 1);
        return new Point2D.Double(p.getX(), p.getY());
    }

}

class PathFollowerPanel extends JPanel
{
    private final PathFollower pathFollower;

    PathFollowerPanel(PathFollower pathFollower)
    {
        this.pathFollower = pathFollower;
    }

    @Override
    protected void paintComponent(Graphics gr)
    {
        super.paintComponent(gr);
        Graphics2D g = (Graphics2D) gr;
        g.setRenderingHint(
            RenderingHints.KEY_ANTIALIASING,
            RenderingHints.VALUE_ANTIALIAS_ON);

        g.setColor(Color.BLUE);
        g.setStroke(new BasicStroke(3.0f));
        g.draw(pathFollower.getPath());

        g.setColor(Color.RED);
        Point2D p = pathFollower.getCurrentPoint();
        double r = 5;
        g.fill(new Ellipse2D.Double(
            p.getX() - r, p.getY() - r, r + r, r + r));
    }
}