简体   繁体   中英

Unity. how can I get Touch by fingerID?

We have the index of the touches and method Input.GetTouch(int index) which returns Touch. Also we have fingerID property of Touch structure. How can we get a Touch by fingerID?

For getting a specific touch by ID you have to search for it in the existing touches.

private static bool TryGetTouch(int fingerID, out Touch touch)
{
    foreach(var t in Input.touches)
    {
        if(t.fingerID == fingerID)
        {
            touch = t;
            return true;
        }
    }

    // No touch with given ID exists
   touch = default;
   return false;
}

You can also use linq and do eg

using System.Linq;

...

private static bool TryGetTouch(int fingerID, out Touch touch)
{
    try
    {
        touch = Input.touches.First(t => t.fingerID == fingerID);
        return true;
    }
    catch
    {
       // No touch with given ID exists
       touch = default;
       return false;
    }
}

and use it like

if(TryGetTouch (someFingerID, out var touch))
{
    // use touch here
}
else
{
    // probably use a new touch and store its fingerID 
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM