刚刚开始接触leapmotion和unity,还没开始学习脚本的编写,只学习了一些C#的基础语法和unity基础。正巧看到一个手势显示菜单的例子,就给文档做个注释便于自己日后观看复习:
/******************************************************************************
* Copyright (C) Leap Motion, Inc. 2011-2018. *
* Leap Motion proprietary and confidential. *
* *
* Use subject to the terms of the Leap Motion SDK Agreement available at *
* https://developer.leapmotion.com/sdk_agreement, or another agreement *
* between Leap Motion and you, your company or other organization. *
******************************************************************************/
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Events;
namespace Leap.Unity.Examples {
[AddComponentMenu("")]
public class SimpleFacingCameraCallbacks : MonoBehaviour {
public Transform toFaceCamera;
private bool _initialized = false;
private bool _isFacingCamera = false;
public UnityEvent OnBeginFacingCamera;
public UnityEvent OnEndFacingCamera;
void Start() { //对象初始化
if (toFaceCamera != null) initialize();//判断toFaceCamera这个法向量是否存在
}
private void initialize() { //功能初始化
// Set "_isFacingCamera" to be whatever the current state ISN'T, so that we are
// guaranteed to fire a UnityEvent on the first initialized Update().
_isFacingCamera = !GetIsFacingCamera(toFaceCamera, Camera.main);
_initialized = true; //表示功能已经被初始化
}
void Update() { //每帧执行的功能
if (toFaceCamera != null && !_initialized) { //判断法向量是否存在以及是否被初始化过,if没有初始化就初始化
initialize();
}
if (!_initialized) return; //过程出了问题,initialized不为true而是为假。在此暂停
if (GetIsFacingCamera(toFaceCamera, Camera.main, _isFacingCamera ? 0.77F : 0.82F) != _isFacingCamera)
{ //GetIsFacingCamera(toFaceCamera, Camera.main, _isFacingCamera ? 0.77F : 0.82F):_isFacingCamera 为真使用0.77F,为假使用0.82F 微调,更容易进面向相机的范围,进入面向相机以后更容易结束掉
//!= _isFacingCamera:和前一帧面向相机状态相反
_isFacingCamera = !_isFacingCamera;//置反
if (_isFacingCamera)
{//Invoke():如果手掌面向相机,激活 OnBeginFacingCamera---->动画正向执行
OnBeginFacingCamera.Invoke();
}
else
{//同上... ...OnEndFacingCamera----->反向执行
OnEndFacingCamera.Invoke();
}
}
}
public static bool GetIsFacingCamera(Transform facingTransform, Camera camera, float minAllowedDotProduct = 0.8F) { //bool函数判断手掌是否面向摄像机 0.8F,浮点数格式
return Vector3.Dot((camera.transform.position - facingTransform.position).normalized, facingTransform.forward) > minAllowedDotProduct;
//Vector3.Dot()计算两个三维向量的点积
//transform是变换类,除了位置还包括大小、旋转等信息
//camera.transform.position相机坐标
//facingTransform.position手掌坐标(手掌法向量的起点
// facingTransform.forward手掌法向量
//camera.transform.position - facingTransform.position from手掌----->相机 的法向量
//.normalized 调整格式
}
}
}