开发者

Calculate path between two points on the screen in Android

Problem seemed very simple to me at first but now I am stuck.

Scenario I want to move a image on the screen, on a certain path I create. Moving this image is being made on a thread, something like:

@Override
    public void run() {
        Canvas c;
        while (run) {
            c = null;
开发者_StackOverflow            try {
                c = panel.getHolder().lockCanvas(null);
                  synchronized (panel.getHolder()) {

                    panel.updateImageCoordinates();
                    panel.onDraw(c);


                }
            } finally {
                if (c != null) {
                    panel.getHolder().unlockCanvasAndPost(c);
                }
            }
        }

for the Image I want to move I have a List with main points where it should go. Each coordinate has:

 public class Coordinates {
        private int x = 0;
        private int y = 0;
        private int speedX=0;
        private int speedY=0;
}

For example, my first point is -5;-30 and I need to get to second point 50.50. The calculation of next coordinates to draw the image is made on updateImageCoordinates(). My problem is that I don't know how to calculate speedX and speedY so that I get from point A to point B on a straight line. Basically for each execution of updateImageCoorindates() I need to do:

image.currentX= image.currentX+speedX;
image.currentY= image.currentY+speedY
//Check if I reached the B point. if so, move to next point.

I don't know based on knowing the coordinates, how I can calculate the speed on x and Y directions.

I attach a image for exemplification. Any help is appreciated.

Calculate path between two points on the screen in Android


I'm not shure if I've understood your question clearly...

If you are looking for function which will translate PointA into point on line A-B.

Line containing both points will have equation:

-30 = -5*a + b and 50 = 50*a + b so b = -250/11 a = 16/11

so to find next point you have to:

check if x of next point is at left (-1) or right (+1) of the destination point

and calculate next point by:

image.currentX= image.currentX+((-1 or +1)*movement_speed);
image.currentY= image.currentY+16/11*(-1 or +1)*movement_speed + (-250/11)


You'll find the API Demos for Animation useful I think. In particular, check out Custom Evaluator.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜