Unity中TouchScript中有用的接口IGestureD

2018-06-28  本文已影响0人  CodeHunter

今天给大家介绍TouchScript中另外一个非常有用的接口——IGestureDelegate

那么他有什么用呢?比如说我们有这样一个需求,可能在场景中的物体在平时都能响应各种触摸事件。但可能在一段时间内不让他响应触摸或者禁止触摸事件,应该怎样去做呢?

如果按一般思路就可能有一个Manager管理类定义一个公有变量,然后在注册所有触控事件的时候,如果当那个变量为false的时候,就直接return,但这样我们每一个触摸事件都可能需要写这样一段代码来控制。

而如果有了IGestureDelegate这个接口,那就给我们从整个脚本层面去控制一个手势是否能被识别;

A delegate which can be set to and control what this gesture can or can not do.

This is a way to control very precisely how affected gestures work without inheriting from them and overriding their behavior.

首先用一个类继承这个接口

这个接口需要实现三个方法,shouldbegin:是否可以开始识别一个手势

shouldReceiveTouch:是否接受触点

ShouldRecognizeSimultaneously:是否可以让两个手势同时被识别

这样就可以简单申明一个公有变量去改变这个公有变量来控制是否接受手势识别。

然后GestureManger.instance.globaGestureDelegate 等于这个实现的接口。然后用空格来改变是否能识别。

然后你把这个脚本挂在在场景里,你可以让其他物体注册相应的事件。然后通过空格来改变是否接受Tap事件。

完整代码案例如下:

using System.Collections;

using System.Collections.Generic;

using UnityEngine;

// using TouchScript.Gestures;

using TouchScript;

using TouchScript.Gestures;

public class TestGestureDelegate : MonoBehaviour, IGestureDelegate

{

    public Gesture tap;

    public bool isReceive = false;

    public bool ShouldBegin(Gesture gesture)

    {

        if (!isReceive)

        {

            return tap == gesture;

        }

        return isReceive;

    }

    public bool ShouldReceiveTouch(Gesture gesture, TouchPoint touch)

    {

        if (!isReceive)

        {

            return tap == gesture;

        }

        return isReceive;

    }

    public bool ShouldRecognizeSimultaneously(Gesture first, Gesture second)

    {

        return false;

    }

    // Use this for initialization

    void Start()

    {

        GestureManager.Instance.GlobalGestureDelegate = this;

    }

    // Update is called once per frame

    void Update()

    {

        if (Input.GetKeyDown(KeyCode.Space))

        {

            isReceive = !isReceive;

        }

    }

}

上一篇 下一篇

猜你喜欢

热点阅读