Bug with touch movement in a game

I’m working on a 2d platfrom game for android and I’m having some trouble with the touch events. this is my code:


public boolean onTouch(MotionEvent e, int scaledX, int scaledY) {
    if (e.getAction() == MotionEvent.ACTION_DOWN) {
        for (int i = 0; i < object.size(); i++) {
            tempObject = object.get(i);
            if (tempObject.getId() == ObjectId.Player) {
                if (moveRight.contains(scaledX, scaledY)) {
                    Log.d("PlayState", "Move button is pressed!");
                    tempObject.setMovingRight(true);

                } else {
                    tempObject.setMovingRight(false);
                }

            }
        }
    }
    if (e.getAction() == MotionEvent.ACTION_UP) {
        for (int i = 0; i < object.size(); i++) {
            tempObject = object.get(i);
            if (tempObject.getId() == ObjectId.Player) {
                if (moveRight.contains(scaledX, scaledY)) {
                    Log.d("PlayState", "Move button is released!");
                    tempObject.setMovingRight(false);

                }
            }
        }
    }
    return true;
}


When I touch the rectangle and release inside the rectangle it works great. The problem is that if I touch the rectangle and move my finger somewhere else while touching, the character keeps on moving. My question is how can I program it so “movingRight” will only be true while the touch is happening inside the rectangle. Thanks !! :slight_smile:

Consider handling ACTION_CANCEL and ACTION_OUTSIDE as those are additional states that are likely being triggered when dragging outside of a target View. Use a switch statement.

I’m not sure how to do it, could you show me an example or point me to a tutorial?

http://www.homeandlearn.co.uk/java/java_switch_statements.html

They’re used in place of multiple if statements.

switch(myInt){
     case 100:
          break; // Do Stuff & Stop switching
     case 200: 
          break; // Another
}

It can also be used for enumerators ( in your case )

switch(e.getAction()){
     case MotionEvent.ACTION_DOWN: 
           // ...
           break;
     case MotionEvent.ACTION_UP:
           // ...
           break;
}

http://lmgtfy.com/?q=java+switch

But Eucmene explained it very well anyways.

Thanks, but I know how to use switch , I’m not sure how to use the ACTION_CANCEL and ACTION_OUTSIDE events.

Basically as soon as the mouse is down (or finger), start polling any change in X, Y coordinate.

As soon as the X, Y coordinate of the touch goes outside the rectangle, fire the exit event. Same goes for enter.

If that makes sense.