Thursday, 23 May 2019

Fix for ScrollRect multi-touch in Unity?

Currently, ScrollRect is extremely buggy when it comes to multi-touch on mobile devices.

If you try it out yourself, you will see that whenever you place two fingers on the screen, the content will jump around, and produce some unexpected behaviour.

Are there any solutions to this? Currently, this is the only solution I have found, but it is still buggy in some cases, and most importantly, does not determine the average input position (or MultiTouchPosition) for all your fingers on the screen.

Here is my modified version of the MultiTouchScrollRect.cs script from the UnityUIExtensions bitbucket, but it jumps every-time I place my next finger on the screen:

using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.UI;

public class MultiTouchScrollRect : ScrollRect
{
    private int minimumTouchCount = 1, maximumTouchCount = 2, pointerId = -100;

    public Vector2 MultiTouchPosition
    {
        get
        {
            Vector2 position = Vector2.zero;
            for (int i = 0; i < Input.touchCount && i < maximumTouchCount; i++)
            {
                position += Input.touches[i].position;
            }
            position /= ((Input.touchCount <= maximumTouchCount) ? Input.touchCount : maximumTouchCount);
            return position;
        }
    }

    public override void OnBeginDrag(PointerEventData eventData)
    {
        if (Input.touchCount >= minimumTouchCount)
        {
            pointerId = eventData.pointerId;
            eventData.position = MultiTouchPosition;
            base.OnBeginDrag(eventData);
        }
    }
    public override void OnDrag(PointerEventData eventData)
    {
        if (Input.touchCount >= minimumTouchCount)
        {
            eventData.position = MultiTouchPosition;
            if (pointerId == eventData.pointerId)
            {
                base.OnDrag(eventData);
            }
        }
    }
    public override void OnEndDrag(PointerEventData eventData)
    {
        if (Input.touchCount >= minimumTouchCount)
        {
            pointerId = -100;
            eventData.position = MultiTouchPosition;
            base.OnEndDrag(eventData);
        }
    }
}

Thanks for your time!



from Fix for ScrollRect multi-touch in Unity?

No comments:

Post a Comment