Search code examples
javascriptlanguage-agnostichtml5-canvasprocessing

How to move object along the polygons


Suppose (say triangle), I want to move an object from A to B then B to C and then C to A. How can I do this?

I googled a lot, but can't find an example of moving an object (say ball) around polygon. I know, i can done it with bezier curves, but for a simple triangle or rectangle how can I do without it? Please give some pseudo code or code in any language. (prefer JavaScript/Processing).


Solution

  • Interpolate

    You can get the position by using interpolation:

    x = x1 + (x2 - x1) * f;
    y = y1 + (y2 - y1) * f;
    

    where x1, y1 is your first point, x2, y2 your end point.

    f is a value between 0.0 and 1.0 which determines where on the line you are (ie. 0 = beginning, 0.5 is half way, 1 = end).

    When you f = 1 you just go to the next segment in the polygon and reset f to 0.

    Fiddle (JS)

    Pseudo:

    //prepare first segment:
    
    x1 = nextX1;
    y1 = nextY1;
    x2 = nextX2;
    y2 = nextY2;
    
    loop:
        f += speed;  /// f.ex. 0.01
    
        x = x1 + (x2 - x1) * f;
        y = y1 + (y2 - y1) * f;
    
        if f=1 then
            f = 0;
            x1 = nextX1;
            y1 = nextY1;
            x2 = nextX2;
            y2 = nextY2;
    
        repeat loop;
    

    Example in JavaScript (see demo link above for full working example)

    function loop() {
    
        /// leave a trace behind for demo
        ctx.clearRect(x + 1, y + 1, 6, 6);
        
        f += speed;
        
        if (f >= 1) {
            /// initialize next line in polygon (see demo)
            getNextSegment();
        }
    
        /// Here: get x and y based on interpolation       
        x = x1 + (x2 - x1) * f;
        y = y1 + (y2 - y1) * f;    
    
        /// draw something to show position
        ctx.fillRect(x, y, 8, 8);
        
        /// loop
        requestAnimationFrame(loop);
    }
    

    For constant speed calculate distance between start end end point and divide a step value (predefined fixed value) on that distance which you use for speed.