Multitouch System with Input Systems EnhancedTouch
Here I’m going to show you how I used InputSystems EnhancedTouch to create a Multitouch system.
In this tutorial, I create a circle clone in the position where the finger touches and when the finger goes up from the screen the circle gets destroyed.
Enhanced touch support provides automatic finger tracking and touch history recording. It is an API designed for polling, i.e. for querying touch state directly in methods such as
MonoBehaviour.Update
. Enhanced touch support cannot be used in combination with InputActions though both can be used side-by-side.
Okay so first before we start coding we have to add one line to the namespace and it’s called so we can use EnhancedTouch.
We add our variables
- Create a 2D circle
- Make the array have 10 empty slots since that is the maximum amount of fingers that a touchscreen can support.
In the Start function we stash our Camera.main
Before we can use EnhancedTouch we have to Enable the touch support by adding these functions and call EnhancedTouchSupport to use the API.
EnhancedTouchSupport.Enable(); to use the EnhancedTouch API
When a touch event is happening we subscribe and call FingerDown
UnityEngine.InputSystem.EnhancedTouch.onFingerDown += FingerDown;
UnityEngine.InputSystem.EnhancedTouch.onFingerDown += FingerUp;
Then we have to unsubscribe from these events when we take our finger from the screen to prevent memory leaks
Each Touchscreen has a limited number of fingers it supports corresponding to the total number of concurrent touches supported by the screen. Unlike a Touch, a Finger will stay the same and valid for the lifetime of its Touchscreen.
Let’s start doing our FingerDown function
- We need to add the Finger class inside the function so it can take the position of the finger on the screen.
- Create a Vector2 fingerPosition and take the position where you touch.
- Instantiate the circle clone at the position where the finger is being pressed using the Vector2 position we declared before.
- Add the circle clone to the GameObject array so we know which finger created which clone. So when the finger leaves the screen we know which circle clone to destroy.
Remember to add atleast 10 empty spaces inside the GameObject array so it can store the circle clones !
Now let’s create the FingerUp function
- Add again the Finger class in the function and name it finger
- We destroy the circle clone using the finger.index so we know which circle to destroy
- Then we set the array to null where that gameObject was
And now we can test this by using a Touchscreen device.
I hope this helped! It’s been a while since I wrote an article so I hope you understood what I wrote :D
If you are interested in learning how I made a multitouch drag and drop using this code let me know in the comments and I will write it! :)
Thank you for reading this and if there was something you didn’t understand feel free to ask in the comments!