如何翻译操纵杆角度&看到x的力量,我想要移动?

时间:2014-07-23 18:09:01

标签: android game-engine game-physics trigonometry joystick

我使用此操纵杆在屏幕上移动视图,因为我想要进行游戏。

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);

问题是,现在我不知道如何使用该角度和力量移动我想在屏幕上移动的视图。

非常感谢你的帮助

1 个答案:

答案 0 :(得分:1)

最简单的方法是将角度值转换为矢量,如下所示:

x = Math.cos( angle );
y = Math.sin( angle );

PS。确保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;

现在只需按向量的(x,y)移动视图即可。另请注意,根据您的移动方式,您还可以反转x和/或y值的符号。

编辑:
如果您要实时应用移动(即每帧一次),您还需要使用自上次移动后经过的时间(即您的帧时间)来缩放移动。