Error With Touch in Mobile

Error With Touch in Mobile

Hello everyone,

Someone Knows how can I move a GameObject by touch using velocity of Rigidbody2D ?

I use de following code to do this but when I change the position of my finger in screen my GameObject don’t follow.

I want to move my GameObject like Snake X Block but just head of snake without her body,


        if (Input.touches.Length > 0)
        {
            switch (Input.GetTouch(0).phase)
            {
                case TouchPhase.Began:
                    touch = Input.GetTouch(0);
                    currentPosition = Camera.main.ScreenToWorldPoint(touch.position);

                    startTime = Time.time;

                    break;
                case TouchPhase.Moved:
                    touch = Input.GetTouch(0);
                    touchPosition = Camera.main.ScreenToWorldPoint(touch.position);
                    touchPosition.z = 10;
                    //transform.position = touchPosition;
                    Debug.DrawLine(currentPosition, touchPosition, Color.red);
                                                      
                    diference = currentPosition.x - touchPosition.x;
                    newPos.x = transform.position.x - diference;
                                        
                    diffTime = Time.time - startTime;
                    distance = Vector2.Distance(currentPosition, newPos);
                    
                    if (diffTime != 0)//<<<<<
                        speed = distance / diffTime;//<<<<<<<<                                      
                 
                    newPos.y = transform.position.y;
          
                    Debug.DrawLine(quad.transform.position, newPos, Color.red);

                    // rb.velocity = quad.transform.forward + newPos * speed / 4;

                    //quad.transform.position = Vector3.Lerp(quad.transform.position, newPos, 0.1f);

                    

                    break;
                case TouchPhase.Ended:
                    diference = 0;
                    break;
            }

        }

Privacy & Terms