我正在使用这个操纵杆在屏幕上移动 View ,因为我想玩游戏。
https://github.com/zerokol/JoystickView
我可以用这个得到操纵杆运动的角度和力量:
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);
问题是现在我不知道如何使用那个角度和力量来移动我想在屏幕上移动的 View 。
非常感谢您的帮助
最佳答案
最简单的方法是将角度值转换为向量,如下所示:
x = Math.cos( angle );
y = Math.sin( angle );
附言。确保 angle
以弧度为单位。
然后使用以下方法对向量进行归一化:
length = Math.sqrt( (x*x) + (y*y) );
x /= length;
y /= length;
现在您将拥有一个表示杆移动方向的归一化向量(正 x 值指向右侧,正 y 值指向上方)。
一旦你有了这个,你就可以将功率百分比应用于你选择的一些移动速度(moveSpeed
)(基于你希望移动的速度),然后应用结果值(currSpeed
) 到向量:
currSpeed = moveSpeed * ( power / 100.0f );
x *= currSpeed;
y *= currSpeed;
现在只需将 View 移动向量的 (x,y
)。另请注意,根据您想要移动的方式,您还可以反转 x
和/或 y
值的符号。
编辑:
如果您要实时应用运动(即每帧一次),您还需要使用自上次移动以来耗时(即您的帧时间)来缩放运动。
关于android - 如何将操纵杆角度和功率转换为 View x,y 我想移动?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24917804/