Move node along path without PathTransition

前端 未结 1 578
情话喂你
情话喂你 2020-12-11 13:28

Problem

I want to move an object along a Path. The PathTransition works in terms of Duration, but I need to use the movement along the Path in an An

相关标签:
1条回答
  • 2020-12-11 14:02

    PathTransition has a public interpolate method that could be called in any fraction between 0 (start) and 1 (end), but sadly it's not intended for the user, and it can be called only while path transition is running.

    If you have a look at how interpolate works, it uses an internal class called Segment, based on linear segments within the path.

    So the first step is converting your original path into a linear one:

    import java.util.ArrayList;
    import java.util.List;
    import java.util.stream.IntStream;
    import javafx.geometry.Point2D;
    import javafx.scene.shape.ClosePath;
    import javafx.scene.shape.CubicCurveTo;
    import javafx.scene.shape.LineTo;
    import javafx.scene.shape.MoveTo;
    import javafx.scene.shape.Path;
    import javafx.scene.shape.PathElement;
    import javafx.scene.shape.QuadCurveTo;
    
    /**
     *
     * @author jpereda
     */
    public class LinearPath {
    
        private final Path originalPath;
    
        public LinearPath(Path path){
            this.originalPath=path;
        }
    
        public Path generateLinePath(){
            /*
            Generate a list of points interpolating the original path
            */
            originalPath.getElements().forEach(this::getPoints);
    
            /*
            Create a path only with MoveTo,LineTo
            */
            Path path = new Path(new MoveTo(list.get(0).getX(),list.get(0).getY()));
            list.stream().skip(1).forEach(p->path.getElements().add(new LineTo(p.getX(),p.getY())));
            path.getElements().add(new ClosePath());
            return path;
        }
    
        private Point2D p0;
        private List<Point2D> list;
        private final int POINTS_CURVE=5;
    
        private void getPoints(PathElement elem){
            if(elem instanceof MoveTo){
                list=new ArrayList<>();
                p0=new Point2D(((MoveTo)elem).getX(),((MoveTo)elem).getY());
                list.add(p0);
            } else if(elem instanceof LineTo){
                list.add(new Point2D(((LineTo)elem).getX(),((LineTo)elem).getY()));
            } else if(elem instanceof CubicCurveTo){
                Point2D ini = (list.size()>0?list.get(list.size()-1):p0);
                IntStream.rangeClosed(1, POINTS_CURVE).forEach(i->list.add(evalCubicBezier((CubicCurveTo)elem, ini, ((double)i)/POINTS_CURVE)));
            } else if(elem instanceof QuadCurveTo){
                Point2D ini = (list.size()>0?list.get(list.size()-1):p0);
                IntStream.rangeClosed(1, POINTS_CURVE).forEach(i->list.add(evalQuadBezier((QuadCurveTo)elem, ini, ((double)i)/POINTS_CURVE)));
            } else if(elem instanceof ClosePath){
                list.add(p0);
            } 
        }
    
        private Point2D evalCubicBezier(CubicCurveTo c, Point2D ini, double t){
            Point2D p=new Point2D(Math.pow(1-t,3)*ini.getX()+
                    3*t*Math.pow(1-t,2)*c.getControlX1()+
                    3*(1-t)*t*t*c.getControlX2()+
                    Math.pow(t, 3)*c.getX(),
                    Math.pow(1-t,3)*ini.getY()+
                    3*t*Math.pow(1-t, 2)*c.getControlY1()+
                    3*(1-t)*t*t*c.getControlY2()+
                    Math.pow(t, 3)*c.getY());
            return p;
        }
    
        private Point2D evalQuadBezier(QuadCurveTo c, Point2D ini, double t){
            Point2D p=new Point2D(Math.pow(1-t,2)*ini.getX()+
                    2*(1-t)*t*c.getControlX()+
                    Math.pow(t, 2)*c.getX(),
                    Math.pow(1-t,2)*ini.getY()+
                    2*(1-t)*t*c.getControlY()+
                    Math.pow(t, 2)*c.getY());
            return p;
        }
    }
    

    Now, based on PathTransition.Segment class, and removing all the private or deprecated API, I've come up with this class with a public interpolator method:

    import java.util.ArrayList;
    import javafx.geometry.Bounds;
    import javafx.scene.Node;
    import javafx.scene.shape.ClosePath;
    import javafx.scene.shape.LineTo;
    import javafx.scene.shape.MoveTo;
    import javafx.scene.shape.Path;
    
    /**
     * Based on javafx.animation.PathTransition
     * 
     * @author jpereda
     */
    public class PathInterpolator {
    
        private final Path originalPath;
        private final Node node;
    
        private double totalLength = 0;
        private static final int SMOOTH_ZONE = 10;
        private final ArrayList<Segment> segments = new ArrayList<>();
        private Segment moveToSeg = Segment.getZeroSegment();
        private Segment lastSeg = Segment.getZeroSegment();
    
        public PathInterpolator(Path path, Node node){
            this.originalPath=path;
            this.node=node;
            calculateSegments();
        }
    
        private void calculateSegments() {
            segments.clear();
            Path linePath = new LinearPath(originalPath).generateLinePath();
            linePath.getElements().forEach(elem->{
                Segment newSeg = null;
                if(elem instanceof MoveTo){
                    moveToSeg = Segment.newMoveTo(((MoveTo)elem).getX(),((MoveTo)elem).getY(), lastSeg.accumLength);
                    newSeg = moveToSeg;
                } else if(elem instanceof LineTo){
                    newSeg = Segment.newLineTo(lastSeg, ((LineTo)elem).getX(),((LineTo)elem).getY());
                } else if(elem instanceof ClosePath){
                    newSeg = Segment.newClosePath(lastSeg, moveToSeg);
                    if (newSeg == null) {
                        lastSeg.convertToClosePath(moveToSeg);
                    }
                }
                if (newSeg != null) {
                    segments.add(newSeg);
                    lastSeg = newSeg;
                }
            });
            totalLength = lastSeg.accumLength;
        }
    
        public void interpolate(double frac) {
            double part = totalLength * Math.min(1, Math.max(0, frac));
            int segIdx = findSegment(0, segments.size() - 1, part);
            Segment seg = segments.get(segIdx);
    
            double lengthBefore = seg.accumLength - seg.length;
    
            double partLength = part - lengthBefore;
    
            double ratio = partLength / seg.length;
            Segment prevSeg = seg.prevSeg;
            double x = prevSeg.toX + (seg.toX - prevSeg.toX) * ratio;
            double y = prevSeg.toY + (seg.toY - prevSeg.toY) * ratio;
            double rotateAngle = seg.rotateAngle;
    
            // provide smooth rotation on segment bounds
            double z = Math.min(SMOOTH_ZONE, seg.length / 2);
            if (partLength < z && !prevSeg.isMoveTo) {
                //interpolate rotation to previous segment
                rotateAngle = interpolate(
                        prevSeg.rotateAngle, seg.rotateAngle,
                        partLength / z / 2 + 0.5F);
            } else {
                double dist = seg.length - partLength;
                Segment nextSeg = seg.nextSeg;
                if (dist < z && nextSeg != null) {
                    //interpolate rotation to next segment
                    if (!nextSeg.isMoveTo) {
                        rotateAngle = interpolate(
                                seg.rotateAngle, nextSeg.rotateAngle,
                                (z - dist) / z / 2);
                    }
                }
            }
            node.setTranslateX(x - getPivotX());
            node.setTranslateY(y - getPivotY());
            node.setRotate(rotateAngle);
        }
    
        private double getPivotX() {
            final Bounds bounds = node.getLayoutBounds();
            return bounds.getMinX() + bounds.getWidth()/2;
        }
    
        private double getPivotY() {
            final Bounds bounds = node.getLayoutBounds();
            return bounds.getMinY() + bounds.getHeight()/2;
        }
    
        /**
         * Returns the index of the first segment having accumulated length
         * from the path beginning, greater than {@code length}
         */
        private int findSegment(int begin, int end, double length) {
            // check for search termination
            if (begin == end) {
                // find last non-moveTo segment for given length
                return segments.get(begin).isMoveTo && begin > 0
                        ? findSegment(begin - 1, begin - 1, length)
                        : begin;
            }
            // otherwise continue binary search
            int middle = begin + (end - begin) / 2;
            return segments.get(middle).accumLength > length
                    ? findSegment(begin, middle, length)
                    : findSegment(middle + 1, end, length);
        }
        /** Interpolates angle according to rate,
         *  with correct 0->360 and 360->0 transitions
         */
        private static double interpolate(double fromAngle, double toAngle, double ratio) {
            double delta = toAngle - fromAngle;
            if (Math.abs(delta) > 180) {
                toAngle += delta > 0 ? -360 : 360;
            }
            return normalize(fromAngle + ratio * (toAngle - fromAngle));
        }
    
        /** Converts angle to range 0-360
         */
        private static double normalize(double angle) {
            while (angle > 360) {
                angle -= 360;
            }
            while (angle < 0) {
                angle += 360;
            }
            return angle;
        }
    
        private static class Segment {
    
            private static final Segment zeroSegment = new Segment(true, 0, 0, 0, 0, 0);
            boolean isMoveTo;
            double length;
            // total length from the path's beginning to the end of this segment
            double accumLength;
            // end point of this segment
            double toX;
            double toY;
            // segment's rotation angle in degrees
            double rotateAngle;
            Segment prevSeg;
            Segment nextSeg;
    
            private Segment(boolean isMoveTo, double toX, double toY,
                    double length, double lengthBefore, double rotateAngle) {
                this.isMoveTo = isMoveTo;
                this.toX = toX;
                this.toY = toY;
                this.length = length;
                this.accumLength = lengthBefore + length;
                this.rotateAngle = rotateAngle;
            }
    
            public static Segment getZeroSegment() {
                return zeroSegment;
            }
    
            public static Segment newMoveTo(double toX, double toY,
                    double accumLength) {
                return new Segment(true, toX, toY, 0, accumLength, 0);
            }
    
            public static Segment newLineTo(Segment fromSeg, double toX, double toY) {
                double deltaX = toX - fromSeg.toX;
                double deltaY = toY - fromSeg.toY;
                double length = Math.sqrt((deltaX * deltaX) + (deltaY * deltaY));
                if ((length >= 1) || fromSeg.isMoveTo) { // filtering out flattening noise
                    double sign = Math.signum(deltaY == 0 ? deltaX : deltaY);
                    double angle = (sign * Math.acos(deltaX / length));
                    angle = normalize(angle / Math.PI * 180);
                    Segment newSeg = new Segment(false, toX, toY,
                            length, fromSeg.accumLength, angle);
                    fromSeg.nextSeg = newSeg;
                    newSeg.prevSeg = fromSeg;
                    return newSeg;
                }
                return null;
            }
    
            public static Segment newClosePath(Segment fromSeg, Segment moveToSeg) {
                Segment newSeg = newLineTo(fromSeg, moveToSeg.toX, moveToSeg.toY);
                if (newSeg != null) {
                    newSeg.convertToClosePath(moveToSeg);
                }
                return newSeg;
            }
    
            public void convertToClosePath(Segment moveToSeg) {
                Segment firstLineToSeg = moveToSeg.nextSeg;
                nextSeg = firstLineToSeg;
                firstLineToSeg.prevSeg = this;
            }
    
        }
    
    }
    

    Basically, once you have a linear path, for every line it generates a Segment. Now with the list of these segments you can call the interpolate method to calculate the position and rotation of the node at any fraction between 0 and 1.

    And finally you can create an AnimationTimer in your application:

    @Override
    public void start(Stage primaryStage) {
        ...
        // move arrow on path
        // --------------------------------------------
        ImageView arrow = createArrow(30,30);
        root.getChildren().add( arrow);
    
        PathInterpolator interpolator=new PathInterpolator(smoothPath, arrow);
    
        AnimationTimer timer = new AnimationTimer() {
    
            @Override
            public void handle(long now) {
                double millis=(now/1_000_000)%10000;
                interpolator.interpolate(millis/10000);
            }
        };
        timer.start();
    }
    
    0 讨论(0)
提交回复
热议问题