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.