Rhach
Rhach

Reputation: 140

Touch Input in Unity remembers the last position

So, I am trying to rotate an object. Pretty straightforward, as soon as the screen is touched, a Vector3 is created, gets the touch position and then, while the user drags their finger on the screen, it does the calculations to rotate the object. When the user removes their finger from the screen, the Vector3 gets destroyed and everything keeps on working fine.

On the editor, it works flawlessly. On an android device howerver, it feels like the device remembers where was the last point that got touched. So, there is no issue on the first time the user tries to rotate the object but, in case they want to rotate it again, the script calculates where the user last tapped and rotates the object as if the user dragged their finger all the way to the new position.

Is there a reason for that? Does the android device store the touch positions? If so, is there a way to reset that? As an extra question, would something similar happen to an iOS device as well?

Edit: The code.

bool topSide;
bool rightSide;
public float rotationSpeed;

void OnMouseDrag()
{
    if (Input.mousePosition.x > Screen.width / 2)
    {
        rightSide = true;
    }
    else
    {
        rightSide = false;
    }

    if (Input.mousePosition.y > Screen.height / 2)
    {
        topSide = true;
    }
    else
    {
        topSide = false;
    }

    if (rightSide)
    {
        rot1 = Input.GetAxis("Mouse Y") * rotationSpeed * Mathf.Deg2Rad;
    }
    else
    {
        rot1 = -Input.GetAxis("Mouse Y") * rotationSpeed * Mathf.Deg2Rad;
    }

    if (topSide)
    {
        rot2 = -Input.GetAxis("Mouse X") * rotationSpeed * Mathf.Deg2Rad;
    }
    else
    {
        rot2 = Input.GetAxis("Mouse X") * rotationSpeed * Mathf.Deg2Rad;
    }
    
    sundial.transform.localEulerAngles += new Vector3(0, 0, (rot1 + rot2) * rotationSpeed * Time.deltaTime);

    rot1 = 0;
    rot2 = 0;
}

Upvotes: 1

Views: 453

Answers (1)

Catlard
Catlard

Reputation: 893

The OnMouseDrag function is probably only meant for the mouse. I usually use some code like this to detect whether something is being clicked on:

public void Update() {
            if(Input.GetMouseButtonDown(0) || Input.GetMouseButton(0)) {
                //raycast to object, check for collision
                //then find angle and store last position, and move the object
            } else if(Input.GetMouseButtonUp(0)) {
                //erase last position and do whatever you do when the user picks up their finger
            }
        }

I realize that this also refers to the mouse button, but I use it all over the place, and it works on mobile/desktop platforms. So if you're worried that it's the platform, try that method instead!

It also involves raycasting, which you aren't doing yet, but it's well worth learning how to do this!

Upvotes: 1

Related Questions