4

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;
        }
}
zkello
  • 239
  • 2
  • 15

2 Answers2

2

Try this It is open source api for on screen joystick for Android.

Dhiral Pandya
  • 10,311
  • 4
  • 47
  • 47
  • 1
    This library works great with some patience. Do *NOT* download the Jar file, it's out dated from the SVN source. Follow the guide and use the "Advanced Method" and the joy stick will work without bugs. The left / right labels are wrong, but it's easy to adjust. Also, make sure you set the width and height in the layout XML. Also, use this for the XML element: – Andy Mar 04 '15 at 20:26
1

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;
zkello
  • 239
  • 2
  • 15
  • This is to move your bitmap, so looks like: _touchingPoint.x = (int) a + initx; _touchingPoint.y = (int) b + inity; – Andy Dec 08 '14 at 15:42