Reputation: 37635
I'm using this joystick to move a view on my screen, because i want to do a game.
https://github.com/zerokol/JoystickView
i can get the angle and the power of the movement of the joystick with this:
joystick.setOnJoystickMoveListener(new OnJoystickMoveListener() {
@Override
public void onValueChanged(int angle, int power, int direction) {
// TODO Auto-generated method stub
angleTextView.setText(" " + String.valueOf(angle) + "°");
powerTextView.setText(" " + String.valueOf(power) + "%");
switch (direction) {
case JoystickView.FRONT:
directionTextView.setText(R.string.front_lab);
break;
case JoystickView.FRONT_RIGHT:
directionTextView.setText(R.string.front_right_lab);
break;
case JoystickView.RIGHT:
directionTextView.setText(R.string.right_lab);
break;
case JoystickView.RIGHT_BOTTOM:
directionTextView.setText(R.string.right_bottom_lab);
break;
case JoystickView.BOTTOM:
directionTextView.setText(R.string.bottom_lab);
break;
case JoystickView.BOTTOM_LEFT:
directionTextView.setText(R.string.bottom_left_lab);
break;
case JoystickView.LEFT:
directionTextView.setText(R.string.left_lab);
break;
case JoystickView.LEFT_FRONT:
directionTextView.setText(R.string.left_front_lab);
break;
default:
directionTextView.setText(R.string.center_lab);
}
}
}, JoystickView.DEFAULT_LOOP_INTERVAL);
The problem is that now i dont know how to use that angle and power to move the view that i want to move in my screen.
Thanks a lot for your help
Upvotes: 4
Views: 1057
Reputation: 18978
Easiest way would be to convert the angle value to a vector, as follows:
x = Math.cos( angle );
y = Math.sin( angle );
PS. Make sure that angle
is in radians.
Then normalize the vector using:
length = Math.sqrt( (x*x) + (y*y) );
x /= length;
y /= length;
Now you will have a normalized vector that represents the direction in which the stick is moved (with positive x values pointing right and positive y values pointing up).
Once you have this you can apply the power percentage to some movement speed (moveSpeed
) you choose (based on how fast you want the movement to be) and then apply the resulting value (currSpeed
) to the vector:
currSpeed = moveSpeed * ( power / 100.0f );
x *= currSpeed;
y *= currSpeed;
Now just move the view by the (x,y
) of the vector. Also note that depending on how you want to move you can also invert the signs of the x
and/or y
values.
Edit:
If you are going to apply the movement in realtime (i.e. once per frame) you will also need to use elapsed time since last move (i.e. you frame time) to scale the movement.
Upvotes: 1