guennin
guennin

Reputation: 21

Dragging objects using ACTION_MOVE

I am trying to make all my drawn Sprites dragable for a little game. It should be able to touch anywhere and the sprites should move the same distance, the finger moves.

With the following method they will move on an ACTION_MOVE event, but only very slow, a shorter distance and sometimes they dont: addToX/Y only adds the gap to the coordinates of the sprites

@Override
public boolean onTouchEvent(MotionEvent evt){
    switch(evt.getAction()){
        case MotionEvent.ACTION_DOWN:
        break;

    case MotionEvent.ACTION_MOVE:
        if(getHistorySize() > 0){
            for(int i = 1, n = evt.getHistorySize(); i < n; i++){
                int calcX = (int) getHistoricalX(i) - (int) getHistoricalX(i-1);
                int calcY = (int) getHistoricalY(i) - (int) getHistoricalY(i-1);
                for(Sprite sprite : spriteList) {
                    sprite.addToX(calcX);
                    sprite.addToY(calcY);
                }
            }
        }
    return true;
}

Any ideas on this?

Upvotes: 2

Views: 431

Answers (1)

Turix
Turix

Reputation: 4490

Assuming your Sprite class is an (potentially-indirect) extension of android.view.View, then you can use setOnDragListener() to define an onDrag() override for them. Then you can use startDrag(...) on them to begin the drag. This is typically triggered by a long-press gesture on the view to be dragged, but in your case you can trigger it from within onTouchEvent() in ACTION_MOVE once (or even ACTION_DOWN). See here for more details on these methods.

Also, with respect to the code you posted, one issue with it that probably explains why it doesn't always work is that you are only using the historical points (which may or may not have accumulated on any particular call to onTouchEvent()). Whether or not getHistorySize() is greater than 0, you should still also use evt.getX() and evt.getY() on each call to onTouchEvent(). But of course, if you use the drag listener approach I suggested instead, you won't need to worry about this.


Update per comment

If you want to move all of the sprites at once, you can put the sprites into a full-screen FrameLayout and attach a GestureDetector that uses a GestureDetector.SimpleOnGestureListener to capture onScroll() callbacks and then calls scrollTo() on the FrameLayout. When the parent FrameLayout scrolls, all of its children sprites will appear to move together.

Upvotes: 1

Related Questions