Why is my dragging method lagging?

48 views Asked by At

I am using the onTouchEvent() method with the following case:

case MotionEvent.ACTION_MOVE:
                if (motionEvent.getHistorySize() > 0) {
                    for (int i = 1, n = motionEvent.getHistorySize(); i < n; i++) {
                        int calcX = (int) motionEvent.getHistoricalX(i) - (int) motionEvent.getHistoricalX(i - 1);
                        treesX += calcX;
                    }
                }
break;

The treesX variable represents the point at which the background is drawn as a bitmap, and another background is drawn next to it with the screen width added to treesX, and after the screen width has been scrolled both images jump one screen width back to give the effect of a seamless background, as the following code shows:

public void draw() {
        if (ourHolder.getSurface().isValid()) {
            canvas = ourHolder.lockCanvas();

            if ((int) treesX < -screenWidth) {
                treesX += screenWidth;
            }
            if ((int) treesX > 0) {
                treesX -= screenWidth;
            }
            canvas.drawBitmap(trees, null, new Rect((int) treesX, 0, screenWidth + (int) treesX, screenHeight), paint);
            canvas.drawBitmap(trees, null, new Rect((int) treesX + screenWidth, 0, 2 * screenWidth + (int) treesX, screenHeight), paint);

            }
            ourHolder.unlockCanvasAndPost(canvas);
        }

This means that the two backgrounds should always be right next to each other, however when I scroll the screen, they come apart slightly or overlap slightly, is there any way I can rectify this? Any part of the code that is causing them to be out of sync?

1

There are 1 answers

0
Karakuri On

When the user drags, you will receive many MotionEvents with ACTION_MOVE. Each event will have a larger history size than the last. This means your for loop will take longer to execute the more the user drags or the longer they keep their finger down.

There's really no need for you to loop over all the historical values just to figure out the current distance that has been dragged. Simply save the X value of the initial ACTION_DOWN, and then on each ACTION_MOVE you compare the most recent X value against the saved one.