How to move object along the polygons

ⅰ亾dé卋堺 提交于 2019-12-11 03:34:35

问题


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).


回答1:


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.



来源:https://stackoverflow.com/questions/19038608/how-to-move-object-along-the-polygons

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!