3

我试图确定用户在屏幕上以圆周运动的方式旋转手指。我目前正在尝试使用叉积并使用 z 组件来确定用户旋转的方式。这产生的结果适用于旋转的下半部分,而在旋转的上半部分则相反。

谁能阐明我做错了什么?

if ( ( Input.touchCount > 0 && Input.GetTouch(0).phase == TouchPhase.Moved && GameStateManager.CurrentGameState == GameState.Minigame) )
    {
        Vector3 touchPos = Vector3.zero;
        if( Camera.mainCamera != null )
        {
            touchPos = Camera.mainCamera.ScreenToWorldPoint( new Vector3( Input.GetTouch(0).position.x, Input.GetTouch(0).position.y, Camera.mainCamera.nearClipPlane ));
        }

        if( prevTouchPos == Vector2.zero )
        {
            prevTouchPos = new Vector2( touchPos.x, touchPos.y );
            return;
        }

        //need angle between last finger position and this finger position
        Vector2 prevVec = new Vector2( prevTouchPos.x - transform.position.x, prevTouchPos.y - transform.position.y );
        Vector2 currVec = new Vector2( touchPos.x - transform.position.x, touchPos.y - transform.position.y );

        float ang = Vector2.Angle(prevVec, currVec);
        Vector3 cross = Vector3.Cross( new Vector3(prevVec.x, prevVec.y, 0), new Vector3(currVec.x, currVec.y, 0));

        Debug.Log(cross.normalized);
        if (cross.z < 0)
        {
            Debug.Log("Prev Vec: " + prevVec);
            Debug.Log("Curr Vec: " + currVec);

            Debug.Log("ROTATE RIGHT");
            transform.Rotate( 0, 0, ang);
        }
        else
        {
            Debug.Log("Prev Vec: " + prevVec);
            Debug.Log("Curr Vec: " + currVec);
            Debug.Log("ROTATE LEFT");
            transform.Rotate( 0, 0, -ang);
        }

        //Debug.Log(ang);
        //Debug.Log( "TouchPos: " + touchPos );




        prevTouchPos = new Vector2( touchPos.x, touchPos.y);
    }
4

1 回答 1

0

我过去做过类似的事情,看起来你很接近,这是我使用的代码,它确定用户是否在一个方向或另一个方向完成了完整的 360。请注意,这是在 C++ 中,但这个想法应该会有所帮助。

            thumbDir.Cross( thumbCur, thumbPrev );
    float z = clamp( thumbDir.z, -1.0f, 1.0f );
    float theta = asin( z );

    if ( z > 0.0f )
    {
        // clockwise
        if ( fDegrees > 0.0f )
            fDegrees = -theta; // Reset angle if changed
        else
            fDegrees -= theta;
    }
    else if ( z < 0.0f )
    {
        // counter-clockwise
        if ( fDegrees < 0.0f )
            fDegrees = -theta;  //Reset angle if changed
        else
            fDegrees -= theta;
    }
于 2014-06-18T21:10:25.323 回答