Search code examples
javaandroidmulti-touchjoystick

Android onscreen joystick issues


So I'm trying to build a game with an on-screen joystick that moves a bitmap around the screen. But when I hold the joystick down in any direction and keep it there, the bitmap will stop moving as well. Its only when I am moving the joystick does the bitmap move. Basically I want to be able to hold down the joystick in say the left position and have the bitmap move left until I let go. Everything else in the code works. Any suggestions?

public boolean onTouch(View v, MotionEvent event) { 
        if (event.getAction() == MotionEvent.ACTION_DOWN)
            _dragging = true;
        else if (event.getAction() == MotionEvent.ACTION_UP)
            _dragging = false;

        _touchingPoint = new Point();

        if (_dragging) {
            // get the pos
            int x = (int) event.getX();
            int y = (int) event.getY();
            _touchingPoint.x = x;
            _touchingPoint.y = y;

            double a = _touchingPoint.x - initx;
            double b = _touchingPoint.y - inity;
            controllerDistance = Math.sqrt((a * a) + (b * b));

            if (controllerDistance > 75) {
                a = (a / controllerDistance) * 75;
                b = (b / controllerDistance) * 75;
                _touchingPoint.x = (int) a + initx;
                _touchingPoint.y = (int) b + inity;
            }

            bitmapPoint.x += a * .05;
            bitmapPoint.y += b * .05;

        } else if (!_dragging) {
            // Snap back to center when the joystick is released
            _touchingPoint.x = initx;
            _touchingPoint.y = inity;
        }
}

Solution

  • It was because I only had the code to increment the bitmaps location in the onTouch method. When the screen is being touched but not moving a event is not registered. The code below should be outside the onTouch method.

    bitmapPoint.x += a * .05;
    bitmapPoint.y += b * .05;