0

I'm having trouble getting my program in Android Studio to properly constrain the joystick I have created. I have two ImageViews placed on top of one another, one being the joystick itself and one being the base of the joystick. Here is the code:

 case R.id.analogStick:
                switch(me.getAction() & MotionEvent.ACTION_MASK) {
                    case MotionEvent.ACTION_DOWN:
                        x = me.getRawX();
                        y = me.getRawY();
                        System.out.println(x);
                        System.out.println(y);
                        dx = x - v.getX();
                        dy = y - v.getY();
                        break;
                    case MotionEvent.ACTION_UP:
                        v.setX(originX);
                        v.setY(originY);
                        break;
                    case MotionEvent.ACTION_CANCEL:
                        break;
                    case MotionEvent.ACTION_MOVE:
                       float xx = originX - me.getRawX();
                       float yy = originY - me.getRawY();
                       float displacement = (float) Math.sqrt((xx * xx) + (yy * yy));
                        if (displacement < baseRadius) {
                            v.setX(me.getRawX() - dx);
                            v.setY(me.getRawY() - dy);
                        }
                        else {
                            float ratio = (float) baseRadius / displacement;
                            float constrainedX = originX + (me.getRawX() - originX) * ratio;
                            float constrainedY = originY + (me.getRawY() - originY) * ratio;
                            v.setX(constrainedX);
                            v.setY(constrainedY);

                        }
                        break;
                }
                break; 

The main problem here is when calculating the displacement. The value turns out to be too high even when within bounds of the baseRadius, so the program always goes to the else statement, executing the constrained joystick case at all times. I get the base radius by the following formula: baseRadius = baseJoystickImage.getWidth() / 2, with baseJoystickImage being an ImageView variable. I'm not sure what could be going wrong here, any help would be appreciated.

worker_bee
  • 451
  • 4
  • 11
  • I noticed that you are using dx, dy for calculating the displacement. Is this something you are initializing properly and storing it within the object for future reference? – worker_bee Jul 24 '17 at 00:07
  • I think you confused dx and dy for xx and yy. Sorry, I should probably rename those variables to something better. But no, dx and dy are not used for calculating displacement but to keep the analog image near the user's thumb at all times, they're unrelated. – Bisquick Quick Jul 24 '17 at 02:22

0 Answers0