简体   繁体   中英

Android Studio - Get bottom 5th of Screen on Y co-ordinate

I am trying to implement a touch event on my simple 2d game. I am trying to do something similar to this quick diagram I made in paint.

触摸图表

For eg, if the user presses on the 'TOP' portion of the screen, the object moves up. If they press right, the object moves right etc.

However, I can't seem to figure out the maths required to select the bottom and the right sections of the screen.

ScreenX and ScreenY variables are the screen size, for reference.

Could somebody check my code and see what I have done wrong?

Java code

@Override
            public boolean onTouchEvent(MotionEvent event)  {
            float x = event.getX();
            float y = event.getY();
        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                if (event.getY() < screenY / 5)
                    tank.changeDirection('UP');
                else if (event.getY() > screenY / 5)
                    tank.changeDirection('DOWN');
                else if (event.getX() < screenX / 2)
                    tank.changeDirection('LEFT');

                else if (event.getX() > screenX / 2)
                    tank.changeDirection('RIGHT');
                break;

            case MotionEvent.ACTION_UP:
                tank.changeDirection(0);
                break;
        }
        return true;
    }

Probably the "down" condition should be

//else if (event.getY() > screenY / 5) 
//    tank.changeDirection('DOWN');

else if (event.getY() > screenY * 4 / 5) 
    tank.changeDirection('DOWN');

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM