Search code examples
androidiosunity-game-enginetouchmove

Touch and move gameobject with 2 fingers


Im new to unity and im trying to build a way to move a gameobject on the scene along the x and z axises by 2 finger touch. Ive come up with a code which i belive is logically correct but does not meet the requirement. Please point my mistake and show me the best way to do it this is the code ive come up with

if (Input.touchCount == 2) {
            // Two fingers
            Touch touch_1 = Input.GetTouch (0);
            Touch touch_2 = Input.GetTouch (1);

            mFingerPosition_1 = touch_1.position;
            mFingerPosition_2 = touch_2.position;
            mMidValue = (mFingerPosition_1 + mFingerPosition_2) / 2;



            //is moving

            if ((touch_1.phase == TouchPhase.Began)&&(touch_2.phase==TouchPhase.Began)) 
            {
                move = true;
            }
            else if ((touch_1.phase == TouchPhase.Ended)||(touch_2.phase==TouchPhase.Ended)) 
            {
                move = false;
            }

            //if moving

            if(move==true)
            {
                Vector2 Axis = touch_1.position - mFingerPosition_1;
                float yAxis = speed * touch_1.deltaPosition.y;
                float xAxis = speed * touch_1.deltaPosition.x;

                //moving on z axis
                if ((Axis.y > 0)||(Axis.y<0))
                {
                    float x = mARObject.transform.position.x;
                    float y = mARObject.transform.position.y;
                    float z = mARObject.transform.position.z;
                    mARObject.transform.position.Set (x,y,yAxis+z);
                }

                //moving on x axis
                else if((Axis.x>0)||(Axis.x<0))
                {
                    float x = mARObject.transform.position.x;
                    float y = mARObject.transform.position.y;
                    float z = mARObject.transform.position.z;
                    mARObject.transform.position.Set (xAxis+x,y,z);
                }
            }

            }

thank you in advance


Solution

  • Vector2 Axis = touch_1.position - mFingerPosition_1; will always result in a delta vector of (0,0) as touch_1.position = mFingerPosition_1. Instead try using Touch.deltaPosition