移动体onSceneTouchEvent

时间:2013-03-12 09:53:15

标签: android andengine game-physics

我正在尝试将一个物体从其初始位置移动到onTouchEvent x和y。问题是身体朝着错误的方向移动。有人能告诉我我的错误在哪里吗?

到目前为止,这是我的代码:

public boolean onPlayerTouchEvent(final Scene pScene,
                    final TouchEvent pSceneTouchEvent) {

            final float pValueX = pSceneTouchEvent.getX();
            final float pValueY = pSceneTouchEvent.getY();
            final float rotation = (float) Math.atan2(pValueX, pValueY);
            final float xComp = (float) Math.sin(rotation);
            final float yComp = (float) Math.cos(rotation);

            if (pSceneTouchEvent.isActionDown()) {
                    this.mPlayerBody.setLinearVelocity(new Vector2(xComp, yComp));
            } else if (pSceneTouchEvent.isActionMove()) {

            } else if (pSceneTouchEvent.isActionUp()) {
                    this.mPlayerBody.setLinearVelocity(new Vector2(0, 0));
            }

            return true;
    }

1 个答案:

答案 0 :(得分:2)

您的旋转(角度)方程错误。

尝试以下代码。 // touchX和touchY全局变量

public boolean onPlayerTouchEvent(final Scene pScene,
                final TouchEvent pSceneTouchEvent) {

     if (pSceneTouchEvent.isActionDown()) {
        touchX = pSceneTouchEvent.getX();
        touchY = pSceneTouchEvent.getY();

    } else if (pSceneTouchEvent.isActionMove()) {
        final float pValueX = pSceneTouchEvent.getX()-touchX ;
        final float pValueY = pSceneTouchEvent.getY()- touchY;
        final float rotation = (float) Math.atan2(pValueY, pValueX);
        final float xComp = (float) Math.cos(rotation);
        final float yComp = (float) Math.sin(rotation);
        this.myBall.getBallBody().setLinearVelocity(
                new Vector2(xComp, yComp));
    } else if (pSceneTouchEvent.isActionUp()) {
        myBall.getBallBody().setLinearVelocity(new Vector2(0, 0));
    }

        return true;
}