Unity Fingers Gesture Gesture Plugin Tutorial (New)

foreword

A few days ago, the Unity resource mall was engaged in activities to get this plug-in for free, but after reading the online tutorials, they were all older versions, so I decided to learn and record them. Personally, I feel that it is more convenient to use than easy touch, and easy touch has not been updated for a long time.

operate

Run the in-plugin demo scene DemoScene.
insert image description here
Hold down the shift key or ctrl to simulate a two-finger operation. At this time, you don't need to click the left side of the mouse, just move the mouse. If you click, it is a three-finger operation.
Please add image description

Shift+mouse wheel up and down: Simulate two-finger rotation
ctrl+mouse wheel up and down: Simulate two-finger zoom
Please add image description

configure

Open FingersScriptPrefab, the parameters in the panel are used for global control.
insert image description here
Parameters (special ones will be added later):
Default DPI: The sensitivity of gesture triggering. If the value is set too large, the gesture will be delayed to trigger. The default value can be used unless there are special needs.

We can customize what the finger displays by modifying the Touch in the image below.
insert image description here
insert image description here

basic use

First declare the gesture Recognizer.

        private TapGestureRecognizer tapGesture;

Initialize the Recognizer and pass in the callback.

        private void CreateTapGesture()
        {
    
    
            tapGesture = new TapGestureRecognizer();
            tapGesture.StateUpdated += TapGestureCallback; //传入回调
            FingersScript.Instance.AddGesture(tapGesture); //对应的有Remove
        }

Trigger the behavior with the callback passed in.

        private void DoubleTapGestureCallback(DigitalRubyShared.GestureRecognizer gesture)
        {
    
    
            if (gesture.State == GestureRecognizerState.Ended)
            {
    
    
                Debug.Log("Tap");
            }
        }

Commonly used API (refer to case code)

Note that gestures are global and do not need to be selected. If you want to specify a target, you need to bind the target or add your own logical judgment.

StateUpdated : Register the callback event for gestures
tripleTapGesture.StateUpdated += PlatformSpecificViewTapUpdated;

PlatformSpecificView : Specifies the target of the click
tripleTapGesture.PlatformSpecificView = bottomLabel.gameObject;

NumberOfTapsRequired : The number of times the tap gesture is connected. Single-click, double-click, etc. are all distinguished by this
tripleTapGesture.NumberOfTapsRequired = 3;

AddGesture : register gestures
FingersScript.Instance.AddGesture(tripleTapGesture);

GestureRecognizerState : Determine the current execution stage in the gesture callback
if (gesture.State == GestureRecognizerState.Ended)

RequireGestureRecognizerToFail : Adds or removes a gesture that needs to fail. Set to null to clear all gestures that need to fail. For example, the following example means that if the doubleTapGesture gesture is triggered, the tapGesture trigger will fail. In fact, it is to prevent the use of gesture conflicts.
tapGesture.RequireGestureRecognizerToFail = doubleTapGesture;

gesture.FocusX, gesture.FocusY : the screen coordinates of the tap in the callback
DebugText("Double tapped at {0}, {1}", gesture.FocusX, gesture.FocusY);

Direction : Set the sliding direction
swipeGesture.Direction = SwipeGestureRecognizerDirection.Down;

DirectionThreshold : For the set direction, this is the amount of swipe in that direction that must be proportional to the other. For example, a swipe down gesture requires multiple times more movement on the y-axis than moving along the x-axis. The default value is 1.5, which means that the swipe down gesture needs to be 1.5 times larger on the y and x axes. Less than or equal to 1 means any ratio is acceptable. Simply put, the larger the value, the more it needs to fit the target direction.
swipeGesture.DirectionThreshold = directionThreshold; // allow a swipe, regardless of slope

gesture.StartFocusX, gesture.StartFocusY : where the gesture starts
DebugText("Swiped from {0},{1} to {2},{3}; velocity: {4}, {5}", gesture.StartFocusX, gesture.StartFocusY, gesture.FocusX, gesture.FocusY, swipeGesture.VelocityX, swipeGesture.VelocityY);

swipeGesture.VelocityX, swipeGesture.VelocityY : swipe speed (according to focus)
DebugText("Swiped from {0},{1} to {2},{3}; velocity: {4}, {5}", gesture.StartFocusX, gesture.StartFocusY, gesture.FocusX, gesture.FocusY, swipeGesture.VelocityX, swipeGesture.VelocityY);

MinimumNumberOfTouchesToTrack : Set the minimum number of fingers used, generally 1 or 2. Note that not every gesture supports multi-finger
panGesture.MinimumNumberOfTouchesToTrack = 2;

MaximumNumberOfTouchesToTrack : Set the maximum number of fingers used, the default is 1 or 2
longPressGesture.MaximumNumberOfTouchesToTrack = 1;

gesture.DeltaX, gesture.DeltaY : the distance of the gesture displacement
DebugText("Panned, Location: {0}, {1}, Delta: {2}, {3}", gesture.FocusX, gesture.FocusY, gesture.DeltaX, gesture.DeltaY);

scaleGesture.ScaleMultiplier : scale value for finger distance
DebugText("Scaled: {0}, Focus: {1}, {2}", scaleGesture.ScaleMultiplier, scaleGesture.FocusX, scaleGesture.FocusY);

rotateGesture.RotationRadiansDelta : the change in rotation in radians
Earth.transform.Rotate(0.0f, 0.0f, rotateGesture.RotationRadiansDelta * Mathf.Rad2Deg);

AllowSimultaneousExecution : Allows multiple gestures to operate a target at the same time
panGesture.AllowSimultaneousExecution(scaleGesture);
panGesture.AllowSimultaneousExecution(rotateGesture);
scaleGesture.AllowSimultaneousExecution(rotateGesture);

CaptureGestureHandler : Capture the clicked target and handle it. Return false to be penetrable, true to be impenetrable, and null to be the default.

		FingersScript.Instance.CaptureGestureHandler = CaptureGestureHandler;
        private static bool? CaptureGestureHandler(GameObject obj)
        {
    
    
            if (obj.name.StartsWith("PassThrough"))
            {
    
    
                return false;
            }
            else if (obj.name.StartsWith("NoPass"))
            {
    
    
                return true;
            }
            return null;
        }

ComponentTypesToDenyPassThrough (important note) : Sets the types that can block gesture detection in addition to the gesture view. For example, to prevent penetration of the UI.
FingersScript.Instance.ComponentTypesToDenyPassThrough.Add(typeof(UnityEngine.UI.Image));

StartOrResetGesture : Start or reset the gesture. The parameters are gesture, whether the target is displayed on the front (only valid for sprite), camera, the game object that performs the gesture, the displayed sprite, the mode of performing the gesture (whether it is performed on a bound object or an arbitrary object), and the camera received.
FingersScript.StartOrResetGesture(r, BringToFront, Cameras, gameObject, spriteRenderer, GestureRecognizerComponentScriptBase.GestureObjectMode.RequireIntersectWithGameObject, out camera);

ClearTrackedTouchesOnEndOrFail : Whether to clear tracked touches when the gesture ends or fails, defaults to false. Normally set to false
tapGesture.ClearTrackedTouchesOnEndOrFail = true;

AddMask : Add restricted area for gestures. The parameters are collider and gesture. It will only take effect if the target is clicked within the mask range
FingersScript.Instance.AddMask(Mask1, tapGesture);

AllowSimultaneousExecutionWithAllGestures : Allow execution with all other gestures
tapGesture2.AllowSimultaneousExecutionWithAllGestures();

FingersScript.HasInstance : Detects if there is an instance of FingersScript in the scene
if (FingersScript.HasInstance)

ShowTouches : Shows simulated clicks, only do this when debugging, as it interferes with other Canvas
FingersScript.Instance.ShowTouches = true;

Get all objects that can receive rays at the clicked position.

        private void TapGestureUpdated(DigitalRubyShared.GestureRecognizer gesture)
        {
    
    
            if (gesture.State == GestureRecognizerState.Ended)
            {
    
    
                Debug.Log("Tapped on " + gesture.PlatformSpecificView);

                List<UnityEngine.EventSystems.RaycastResult> results = new List<UnityEngine.EventSystems.RaycastResult>();
                UnityEngine.EventSystems.PointerEventData eventData = new UnityEngine.EventSystems.PointerEventData(UnityEngine.EventSystems.EventSystem.current);
                eventData.position = new Vector2(gesture.FocusX, gesture.FocusY);
                UnityEngine.EventSystems.EventSystem.current.RaycastAll(eventData, results);

                Debug.Log("Event system raycast count: " + results.Count + ", objects: " + string.Join(",", results.Select(r => r.gameObject.name).ToArray()));
            }
        }

Component introduction

The parameters are relatively simple, and can be understood by literal translation or viewing the code.

About the joystick

insert image description here
Brief introduction of parameters

DeadZone: Dead zone, less than this value will not trigger the joystick effect. Similar sensitivity

InputCurve: pass-by-value curve

EightAxisMode: Octagonal mode, the joystick will turn into eight directions of up, down, left, right and diagonal, and the joystick rotation has a sense of interval

MaxRangeRadiusMultiplier: The offset when the center circle of the joystick is dragged to the boundary
insert image description here

FollowSpeed: The overall speed of the joystick to follow the finger, the default is 0

StartMode: MustStartInside (the joystick is still, operate on the joystick) MoveToPanStart (according to the Pan gesture as the starting point of the joystick) PanInsideOrPanMovesInside (the joystick is still, operate in the Pan gesture area)

RestrictJoystickPositionTo: requires Unity2019 or above. Constrain the joystick position to this collider2D, null means no limit. Put the colider in the joystick parent

ReturnToHomePosition: automatically return to the initial position after the operation

Cross Platform Input: Input shaft

Callbacks: joystick callback, receive Vector2

Usage
Pass in the callback event for the joystick. Of course, it can also be bound on the panel.
Joystick.JoystickExecuted = JoystickExecuted;

Add a mask to the joystick. (optional)
FingersScript.Instance.AddMask(Mask1, JoystickScript.PanGesture);

Various Gesture components

Check out the DemoSceneComponents scene. The functions on the panel are similar to those described in the previous API.

FingersPanOrbit

Scene: DemoScene3DOrbit
insert image description here
Effect: It can easily realize the rotation, movement and scaling of the target object, and quickly achieve the desired effect by adjusting the parameters.Please add image description

FingersDragDropComponentScript

Long press and drag the object, 3D or sprite, UI can be, but note that only the sprite has the effect of being displayed in the front, you can modify the logic yourself.

The author has made many cases, all of which are extended using the core functions of this plug-in, so I will not describe them one by one here. You can read them by yourself to deepen your understanding.
Other knowledge points will continue to be added later.

Remark

Having a problem, FingersScript conflicts with UICanvas generated in my game frame, Canvas doesn't receive click events.
Solution: Create a UI->EventSystem in the scene, don't generate it dynamically.

Guess you like

Origin blog.csdn.net/qq_39162826/article/details/121661290