Hololens入门之手势识别(使用Navigation gesture控制物体缩放)

Hololens入门之手势识别(使用Navigation gesture控制物体缩放)
本文示例在 Hololens入门之手势识别(手检测反馈) 示例的基础上进行修改Navigation gesture :保持点击手势,在一个标准3D立方空间内相对运动导航手势就像一个虚拟的操纵杆,能够用于UI控件导航,例如弧形菜单。通过点击开始手势,然后在以点击处为中心的标准立方空间中移动手部。你可以沿着X、Y、Z轴移动手部,这会带来数值-1到1的变化,初始位置的值为0.1、修改HandsManager.cs,添加InteractionManager.SourcePressed,InteractionManager.SourceReleased处理函数,用于识别物体被点击和被释放的事件HandsManager.cs完整代码如下:

[csharp] view plain copy

// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See LICENSE in the project root for license information.

using UnityEngine;  
using UnityEngine.VR.WSA.Input;  
  
namespace HoloToolkit.Unity  
{  
    /// <summary>  
    /// HandsManager determines if the hand is currently detected or not.  
    /// </summary>  
    public partial class HandsManager : Singleton<HandsManager>  
    {  
        /// <summary>  
        /// HandDetected tracks the hand detected state.  
        /// Returns true if the list of tracked hands is not empty.  
        /// </summary>  
        public bool HandDetected  
        {  
            get { return trackedHands.Count > 0; }  
        }  
  
        private HashSet<uint> trackedHands = new HashSet<uint>();  
  
        public GameObject FocusedGameObject { get; private set; }  
  
        void Awake()  
        {  
            InteractionManager.SourceDetected += InteractionManager_SourceDetected;  
            InteractionManager.SourceLost += InteractionManager_SourceLost;  
            //来源被按下    
            InteractionManager.SourcePressed += InteractionManager_SourcePressed;  
            //被释放    
            InteractionManager.SourceReleased += InteractionManager_SourceReleased;  
  
            FocusedGameObject = null;  
        }  
  
        //手势释放时,将被关注的物体置空    
        private void InteractionManager_SourceReleased(InteractionSourceState state)  
        {  
            FocusedGameObject = null;  
        }  
        //识别到手指按下时,将凝视射线关注的物体置为当前手势操作的对象    
        private void InteractionManager_SourcePressed(InteractionSourceState state)  
        {  
            if (GazeManager.Instance.FocusedObject != null)  
            {  
                FocusedGameObject = GazeManager.Instance.FocusedObject;  
            }  
        }  
  
        private void InteractionManager_SourceDetected(InteractionSourceState state)  
        {  
            // Check to see that the source is a hand.  
            if (state.source.kind != InteractionSourceKind.Hand)  
            {  
                return;  
            }  
  
            trackedHands.Add(state.source.id);  
        }  
  
        private void InteractionManager_SourceLost(InteractionSourceState state)  
        {  
            // Check to see that the source is a hand.  
            if (state.source.kind != InteractionSourceKind.Hand)  
            {  
                return;  
            }  
  
            if (trackedHands.Contains(state.source.id))  
            {  
                trackedHands.Remove(state.source.id);  
            }  
            FocusedGameObject = null;  
        }  
  
        void OnDestroy()  
        {  
            InteractionManager.SourceDetected -= InteractionManager_SourceDetected;  
            InteractionManager.SourceLost -= InteractionManager_SourceLost;  
  
            InteractionManager.SourceReleased -= InteractionManager_SourceReleased;  
            InteractionManager.SourcePressed -= InteractionManager_SourcePressed;  
        }  
    }  
}  

2、修改GestureManager.cs,订阅Navigation手势事件****[csharp] view plain copy

// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See LICENSE in the project root for license information.

using UnityEngine.VR.WSA.Input;  
  
namespace HoloToolkit.Unity  
{  
    /// <summary>  
    /// GestureManager creates a gesture recognizer and signs up for a tap gesture.  
    /// When a tap gesture is detected, GestureManager uses GazeManager to find the game object.  
    /// GestureManager then sends a message to that game object.  
    /// </summary>  
    [RequireComponent(typeof(GazeManager))]  
    public partial class GestureManager : Singleton<GestureManager>  
    {  
        /// <summary>  
        /// Key to press in the editor to select the currently gazed hologram  
        /// </summary>  
        public KeyCode EditorSelectKey = KeyCode.Space;  
  
        /// <summary>  
        /// To select even when a hologram is not being gazed at,  
        /// set the override focused object.  
        /// If its null, then the gazed at object will be selected.  
        /// </summary>  
        public GameObject OverrideFocusedObject  
        {  
            get; set;  
        }  
  
        /// <summary>  
        /// Gets the currently focused object, or null if none.  
        /// </summary>  
        public GameObject FocusedObject  
        {  
            get { return focusedObject; }  
        }  
  
        public bool IsNavigating { get; private set; }  
        public Vector3 NavigationPosition { get; private set; }  
  
        private GestureRecognizer gestureRecognizer;  
        private GameObject focusedObject;  
  
        void Start()  
        {  
            //  创建GestureRecognizer实例    
            gestureRecognizer = new GestureRecognizer();  
            //  注册指定的手势类型    
            gestureRecognizer.SetRecognizableGestures(GestureSettings.Tap  
                | GestureSettings.NavigationX);  
            //  订阅手势事件    
            gestureRecognizer.TappedEvent += GestureRecognizer_TappedEvent;  
  
            //添加Navigation手势事件    
            gestureRecognizer.NavigationStartedEvent += GestureRecognizer_NavigationStartedEvent;  
            gestureRecognizer.NavigationUpdatedEvent += GestureRecognizer_NavigationUpdatedEvent;  
            gestureRecognizer.NavigationCompletedEvent += GestureRecognizer_NavigationCompletedEvent;  
            gestureRecognizer.NavigationCanceledEvent += GestureRecognizer_NavigationCanceledEvent;  
            //  开始手势识别    
            gestureRecognizer.StartCapturingGestures();  
        }  
  
        private void GestureRecognizer_NavigationCanceledEvent(InteractionSourceKind source, Vector3 normalizedOffset, Ray headRay)  
        {  
            IsNavigating = false;  
        }  
  
        private void GestureRecognizer_NavigationCompletedEvent(InteractionSourceKind source, Vector3 normalizedOffset, Ray headRay)  
        {  
            IsNavigating = false;  
        }  
  
        private void GestureRecognizer_NavigationUpdatedEvent(InteractionSourceKind source, Vector3 normalizedOffset, Ray headRay)  
        {  
            if (HandsManager.Instance.FocusedGameObject != null)  
            {  
                IsNavigating = true;  
                NavigationPosition = normalizedOffset;  
                HandsManager.Instance.FocusedGameObject.SendMessageUpwards("PerformZoomUpdate", normalizedOffset, SendMessageOptions.DontRequireReceiver);  
            }  
        }  
  
        private void GestureRecognizer_NavigationStartedEvent(InteractionSourceKind source, Vector3 normalizedOffset, Ray headRay)  
        {  
            if (HandsManager.Instance.FocusedGameObject != null)  
            {  
                IsNavigating = true;  
                NavigationPosition = normalizedOffset;  
                HandsManager.Instance.FocusedGameObject.SendMessageUpwards("PerformNavigationStart", normalizedOffset, SendMessageOptions.DontRequireReceiver);  
            }  
        }  
  
        private void OnTap()  
        {  
            if (focusedObject != null)  
            {  
                focusedObject.SendMessage("OnSelect", SendMessageOptions.DontRequireReceiver);  
            }  
        }  
  
        private void GestureRecognizer_TappedEvent(InteractionSourceKind source, int tapCount, Ray headRay)  
        {  
            OnTap();  
        }  
  
        void LateUpdate()  
        {  
            GameObject oldFocusedObject = focusedObject;  
  
            if (GazeManager.Instance.Hit &&  
                OverrideFocusedObject == null &&  
                GazeManager.Instance.HitInfo.collider != null)  
            {  
                // If gaze hits a hologram, set the focused object to that game object.  
                // Also if the caller has not decided to override the focused object.  
                focusedObject = GazeManager.Instance.HitInfo.collider.gameObject;  
            }  
            else  
            {  
                // If our gaze doesn't hit a hologram, set the focused object to null or override focused object.  
                focusedObject = OverrideFocusedObject;  
            }  
  
            //if (focusedObject != oldFocusedObject)  
            //{  
            //    // If the currently focused object doesn't match the old focused object, cancel the current gesture.  
            //    // Start looking for new gestures.  This is to prevent applying gestures from one hologram to another.  
            //    gestureRecognizer.CancelGestures();  
            //    gestureRecognizer.StartCapturingGestures();  
            //}  
 
#if UNITY_EDITOR  
            if (Input.GetMouseButtonDown(1) || Input.GetKeyDown(EditorSelectKey))  
            {  
                OnTap();  
            }  
#endif  
        }  
  
        void OnDestroy()  
        {  
            gestureRecognizer.StopCapturingGestures();  
            gestureRecognizer.TappedEvent -= GestureRecognizer_TappedEvent;  
            gestureRecognizer.NavigationStartedEvent -= GestureRecognizer_NavigationStartedEvent;  
            gestureRecognizer.NavigationUpdatedEvent -= GestureRecognizer_NavigationUpdatedEvent;  
            gestureRecognizer.NavigationCompletedEvent -= GestureRecognizer_NavigationCompletedEvent;  
            gestureRecognizer.NavigationCanceledEvent -= GestureRecognizer_NavigationCanceledEvent;  
        }  
    }  
}  

3、新增测试用Cube
[图片上传中。。。(1)]


4、新增修改CubeScript.cs,添加物体缩放函数,当选中物体,左右移动时,物体进行缩放[csharp] view plain copy

using System.Collections;  
using HoloToolkit.Unity;  
  
public class CubeScript : MonoBehaviour {  
  
    private Vector3 navigationPreviousPosition;  
    public float MaxScale = 2f;  
    public float MinScale = 0.1f;  
      
    // Use this for initialization  
    void Start () {  
      
    }  
      
    // Update is called once per frame  
    void Update () {  
      
    }  
  
    void PerformNavigationStart(Vector3 position)  
    {  
        //设置初始位置    
        navigationPreviousPosition = position;  
    }  
  
    void PerformZoomUpdate(Vector3 position)  
    {  
        if (GestureManager.Instance.IsNavigating && HandsManager.Instance.FocusedGameObject == gameObject)  
        {  
            Vector3 deltaScale = Vector3.zero;  
            float ScaleValue = 0.01f;  
            //设置每一帧缩放的大小  
            if (position.x < 0)  
            {  
                ScaleValue = -1 * ScaleValue;  
            }  
            //当缩放超出设置的最大,最小范围时直接返回  
            if (transform.localScale.x >= MaxScale && ScaleValue > 0)  
            {  
                return;  
            }  
            else if (transform.localScale.x <= MinScale && ScaleValue < 0)  
            {  
                return;  
            }  
            //根据比例计算每个方向上的缩放大小  
            deltaScale.x = ScaleValue;  
            deltaScale.y = (transform.localScale.y / transform.localScale.x) * ScaleValue;  
            deltaScale.z = (transform.localScale.z / transform.localScale.x) * ScaleValue;  
            transform.localScale += deltaScale;  
        }  
    }  
}  

5、运行测试启动后手势向左滑动,物体缩小
[图片上传中。。。(2)]
手势向右滑动,物体放大
[图片上传中。。。(3)]

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 219,366评论 6 508
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 93,521评论 3 395
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 165,689评论 0 356
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,925评论 1 295
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,942评论 6 392
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,727评论 1 305
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,447评论 3 420
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 39,349评论 0 276
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,820评论 1 317
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,990评论 3 337
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 40,127评论 1 351
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,812评论 5 346
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,471评论 3 331
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 32,017评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 33,142评论 1 272
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 48,388评论 3 373
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 45,066评论 2 355

推荐阅读更多精彩内容