private bool TryPivot(FingerData fingerData)
        {
            if (fingerData.Buffer.Count > 2)
            {
                var first     = fingerData.Buffer[0];
                var last      = fingerData.Buffer[fingerData.Buffer.Count - 1];
                var bestScore = -1.0f;
                //var bestScoreA      = -1.0f;
                //var bestScoreB      = -1.0f;
                var bestIndex       = -1;
                var bestMiddle      = default(Vector2);
                var shapePointA     = Shape.GetPoint(fingerData.Index + fingerData.Points.Count - 2, fingerData.Reverse);
                var shapePointB     = Shape.GetPoint(fingerData.Index + fingerData.Points.Count - 1, fingerData.Reverse);
                var shapePointC     = Shape.GetPoint(fingerData.Index + fingerData.Points.Count - 0, fingerData.Reverse);
                var shapeDirectionA = (shapePointB - shapePointA).normalized;
                var shapeDirectionB = (shapePointC - shapePointB).normalized;

                for (var i = fingerData.Buffer.Count - 2; i >= 1; i--)
                {
                    var middle = fingerData.Buffer[i];

                    if (Vector2.Distance(first, middle) >= MinimumEdgeLength && Vector2.Distance(middle, last) >= MinimumEdgeLength)
                    {
                        var directionA = (middle - first).normalized;
                        var directionB = (last - middle).normalized;
                        var scoreA     = Mathf.Max(0.0f, Vector2.Dot(directionA, shapeDirectionA));
                        var scoreB     = Mathf.Max(0.0f, Vector2.Dot(directionB, shapeDirectionB));
                        var score      = scoreA * scoreB;

                        if (scoreA > DirectionPrecision && scoreB > DirectionPrecision && score > bestScore)
                        {
                            //bestScoreA = scoreA;
                            //bestScoreB = scoreB;
                            bestScore  = score;
                            bestIndex  = i;
                            bestMiddle = middle;
                        }
                    }
                }

                if (bestIndex > 0)
                {
                    if (BufferOutOfBounds(first, bestMiddle, fingerData, 0, bestIndex) == false)
                    {
                        if (BufferOutOfBounds(bestMiddle, last, fingerData, bestIndex, fingerData.Buffer.Count) == false)
                        {
                            fingerData.Points.Insert(fingerData.Points.Count - 1, bestMiddle);

                            fingerData.Buffer.Clear();

                            fingerData.Buffer.Add(last);

                            return(true);
                        }
                    }
                }
            }

            return(false);
        }
Example #2
0
    // Update is called once per frame
    void Update()
    {
        for (int i = 0; i < 2; i++)
        {
            //含有中指和食指的数据
            if (m_HandData.FingerDatas[i].ContainsKey(Finger.FingerType.TYPE_INDEX) &&
                m_HandData.FingerDatas[i].ContainsKey(Finger.FingerType.TYPE_THUMB))
            {
                FingerData indexFingerData = m_HandData.FingerDatas[i][Finger.FingerType.TYPE_INDEX];
                Vector     indexPos        = indexFingerData.m_Point.m_Position;
                Vector     thumbPos        = m_HandData.FingerDatas[i][Finger.FingerType.TYPE_THUMB].m_Point.m_Position;

                //print("IndexToThumb:" + indexPos.DistanceTo(thumbPos) );
                print((indexFingerData.m_Point.m_Position - indexFingerData.m_Position).AngleTo(indexFingerData.m_Point.m_Direction) * 180 / Mathf.PI);
                if (FingerMatch.StrightState(indexFingerData))
                {
                    m_IsHandPinch[i] = true;
                    m_Distance[i]    = indexPos.DistanceTo(thumbPos);
                }
                else
                {
                    m_IsHandPinch[i] = false;
                    m_Distance[i]    = 0f;
                }
            }
            else
            {
                m_IsHandPinch[i] = false;
                m_Distance[i]    = 0f;
            }
        }
    }
    private FingerData ConstructFingerData(object f)
    {
        FingerData finger = new FingerData();
        Dictionary <string, object> fo = (Dictionary <string, object>)f;

        finger.bases                 = (List <object>)fo["bases"];
        finger.btipPosition          = (List <object>)fo["btipPosition"];
        finger.carpPosition          = (List <object>)fo["carpPosition"];
        finger.dipPosition           = (List <object>)fo["dipPosition"];
        finger.direction             = (List <object>)fo["direction"];
        finger.extended              = (bool)fo["extended"];
        finger.handId                = (long)fo["handId"];
        finger.id                    = (long)fo["id"];
        finger.length                = (double)fo["length"];
        finger.mcpPosition           = (List <object>)fo["mcpPosition"];
        finger.pipPosition           = (List <object>)fo["pipPosition"];
        finger.stabilizedTipPosition = (List <object>)fo["stabilizedTipPosition"];
        finger.timeVisible           = (double)fo["timeVisible"];
        finger.tipPosition           = (List <object>)fo["tipPosition"];
        finger.tipVelocity           = (List <object>)fo["tipVelocity"];
        finger.tool                  = (bool)fo["tool"];
        finger.touchDistance         = (double)fo["touchDistance"];
        finger.type                  = (long)fo["type"];
        finger.width                 = (double)fo["width"];

        return(finger);
    }
Example #4
0
    void SaveFingerDataWithHandIndex(Hand hand)
    {
        bool      isLeft    = hand.IsLeft;
        int       handIndex = isLeft ? 0 : 1;
        JointData meta0;
        JointData prox0;
        JointData inter0;
        JointData dist0;
        JointData dist1;

        foreach (Finger finger in hand.Fingers)
        {
            Finger.FingerType fingerType = finger.Type;

            if (fingerType == Finger.FingerType.TYPE_THUMB)
            {
                meta0 = new JointData(Vector.Zero, Vector.Zero);
            }
            else
            {
                meta0 = GetJointData(finger, Bone.BoneType.TYPE_METACARPAL, 0);
            }
            prox0  = GetJointData(finger, Bone.BoneType.TYPE_PROXIMAL, 0);
            inter0 = GetJointData(finger, Bone.BoneType.TYPE_INTERMEDIATE, 0);
            dist0  = GetJointData(finger, Bone.BoneType.TYPE_DISTAL, 0);
            dist1  = GetJointData(finger, Bone.BoneType.TYPE_DISTAL, 1);

            FingerData finger_data = new FingerData(meta0, prox0, inter0, dist0, dist1);

            SaveFingerData(handIndex, fingerType, finger_data);
        }
    }
Example #5
0
    IEnumerator Start()
    {
        // save original eulers
        SetOriginalEulers(_mThumb);
        SetOriginalEulers(_mIndex);
        SetOriginalEulers(_mMiddle);
        SetOriginalEulers(_mRing);
        SetOriginalEulers(_mPinky);

        if (string.IsNullOrEmpty(_mIPAddress))
        {
            yield break;
        }

        if (PlayerPrefs.HasKey(KEY_STRAIGHT))
        {
            string json = PlayerPrefs.GetString(KEY_STRAIGHT);
            if (!string.IsNullOrEmpty(json))
            {
                _mStraight = JsonUtility.FromJson <FingerData>(json);
            }
        }
        if (PlayerPrefs.HasKey(KEY_FIST))
        {
            string json = PlayerPrefs.GetString(KEY_FIST);
            if (!string.IsNullOrEmpty(json))
            {
                _mFist = JsonUtility.FromJson <FingerData>(json);
            }
        }

        StartCoroutine(DoRequests());
    }
Example #6
0
 private void FillFingerData(FingerData fd, ref int index, float[] array)
 {
     FillVector3(fd.Metacarpal, ref index, array);
     FillVector3(fd.Proximal, ref index, array);
     FillVector3(fd.Distal, ref index, array);
     FillVector3(fd.Tip, ref index, array);
 }
    public void onDown(PointerEventData data)
    {
        if (!checkCanFinger())
        {
            return;
        }

        FingerData obj = new FingerData();

        obj.prePosition            = data.position;
        obj.flag                   = true;
        obj.id                     = data.pointerId;
        fingerPool[data.pointerId] = obj;
        if (Util.checkIsOverUI(dragPanel.gameObject, obj.id))
        {
            obj.flag = false;
            return;
        }

        if (Input.touchCount >= 2)
        {
            return;
        }

        tapStart = true;
    }
Example #8
0
    public void readJointDataFromJson(finger[] a, int hand_type, int finger_type)
    {
        //meta0
        Vector    temp111 = new Vector(float.Parse(a[0].meta0[0].joint_position[0].x), float.Parse(a[0].meta0[0].joint_position[0].y), float.Parse(a[0].meta0[0].joint_position[0].z));
        Vector    temp112 = new Vector(float.Parse(a[0].meta0[0].joint_rotation[0].x), float.Parse(a[0].meta0[0].joint_rotation[0].y), float.Parse(a[0].meta0[0].joint_rotation[0].z));
        JointData joint_m = new JointData(temp111, temp112);
        // prox0
        Vector    temp121 = new Vector(float.Parse(a[0].prox0[0].joint_position[0].x), float.Parse(a[0].prox0[0].joint_position[0].y), float.Parse(a[0].prox0[0].joint_position[0].z));
        Vector    temp122 = new Vector(float.Parse(a[0].prox0[0].joint_rotation[0].x), float.Parse(a[0].prox0[0].joint_rotation[0].y), float.Parse(a[0].prox0[0].joint_rotation[0].z));
        JointData joint_p = new JointData(temp121, temp122);
        // inter0
        Vector    temp131 = new Vector(float.Parse(a[0].inter0[0].joint_position[0].x), float.Parse(a[0].inter0[0].joint_position[0].y), float.Parse(a[0].inter0[0].joint_position[0].z));
        Vector    temp132 = new Vector(float.Parse(a[0].inter0[0].joint_rotation[0].x), float.Parse(a[0].inter0[0].joint_rotation[0].y), float.Parse(a[0].inter0[0].joint_rotation[0].z));
        JointData joint_i = new JointData(temp131, temp132);
        // dist0
        Vector    temp141  = new Vector(float.Parse(a[0].dist0[0].joint_position[0].x), float.Parse(a[0].dist0[0].joint_position[0].y), float.Parse(a[0].dist0[0].joint_position[0].z));
        Vector    temp142  = new Vector(float.Parse(a[0].dist0[0].joint_rotation[0].x), float.Parse(a[0].dist0[0].joint_rotation[0].y), float.Parse(a[0].dist0[0].joint_rotation[0].z));
        JointData joint_d0 = new JointData(temp141, temp142);
        // dist1
        Vector     temp151  = new Vector(float.Parse(a[0].dist1[0].joint_position[0].x), float.Parse(a[0].dist1[0].joint_position[0].y), float.Parse(a[0].dist1[0].joint_position[0].z));
        Vector     temp152  = new Vector(float.Parse(a[0].dist1[0].joint_rotation[0].x), float.Parse(a[0].dist1[0].joint_rotation[0].y), float.Parse(a[0].dist1[0].joint_rotation[0].z));
        JointData  joint_d1 = new JointData(temp151, temp152);
        FingerData finger   = new FingerData(joint_m, joint_p, joint_i, joint_d0, joint_d1);

        m_FingerDatas[hand_type][finger_Type[finger_type]] = finger;
    }
        private void onPreview(FingerData fingerData)
        {
            Thread trd = new Thread(() =>
            {
                try
                {
                    if (previewState == "Finger1")
                    {
                        if (fingerData != null)
                        {
                            pbFinger1.Image = fingerData.FingerImage;
                            pbFinger1.Refresh();
                        }
                    }
                    else if (previewState == "Finger2")
                    {
                        if (fingerData != null)
                        {
                            pbFinger2.Image = fingerData.FingerImage;
                            pbFinger2.Refresh();
                        }
                    }
                }
                catch (Exception ex)
                {
                }
            });

            trd.Start();
        }
        protected virtual void UpdateLine(FingerData fingerData, LeanFinger finger, LineRenderer line)
        {
            var color0 = StartColor;
            var color1 = EndColor;

            if (finger != null)
            {
                // Reserve one point for each snapshot
                line.positionCount = finger.Snapshots.Count;

                // Loop through all snapshots
                for (var i = 0; i < finger.Snapshots.Count; i++)
                {
                    var snapshot = finger.Snapshots[i];

                    // Get the world postion of this snapshot
                    var worldPoint = ScreenDepth.Convert(snapshot.ScreenPosition, gameObject);

                    // Write position
                    line.SetPosition(i, worldPoint);
                }
            }
            else
            {
                fingerData.Age += Time.deltaTime;

                var alpha = Mathf.InverseLerp(FadeTime, 0.0f, fingerData.Age);

                color0.a *= alpha;
                color1.a *= alpha;
            }

            line.startColor = color0;
            line.endColor   = color1;
        }
Example #11
0
        protected override void UpdateLine(FingerData fingerData, LeanFinger finger, LineRenderer line)
        {
            var color0 = StartColor;
            var color1 = EndColor;
            var width  = fingerData.Width;

            if (finger != null)
            {
                // Reserve points
                line.positionCount = 2;

                // Calculate preliminary points
                var point0 = ScreenDepth.Convert(finger.StartScreenPosition, gameObject);
                var point1 = ScreenDepth.Convert(finger.ScreenPosition, gameObject);

                if (StartAtOrigin == true)
                {
                    point0 = transform.position;
                }

                // Get length, and clamp?
                var length = Vector3.Distance(point0, point1);

                if (LengthMin >= 0.0f && length < LengthMin)
                {
                    length = LengthMin;
                }

                if (LengthMax >= 0.0f && length > LengthMax)
                {
                    length = LengthMax;
                }

                // Write straight line
                line.SetPosition(0, point0);
                line.SetPosition(1, point0 + Vector3.Normalize(point1 - point0) * length);
            }
            else
            {
                fingerData.Age += Time.deltaTime;

                var alpha = Mathf.InverseLerp(FadeTime, 0.0f, fingerData.Age);

                color0.a *= alpha;
                color1.a *= alpha;
            }

            if (WidthScale != 0.0f && line.positionCount == 2)
            {
                var point0 = line.GetPosition(0);
                var point1 = line.GetPosition(1);
                var length = Vector3.Distance(point0, point1);

                width += length * WidthScale;
            }

            line.startColor      = color0;
            line.endColor        = color1;
            line.widthMultiplier = width;
        }
Example #12
0
 public FingerData(FingerData f_data)
 {
     meta0  = f_data.meta0;
     prox0  = f_data.prox0;
     inter0 = f_data.inter0;
     dist0  = f_data.dist0;
     dist1  = f_data.dist1;
 }
Example #13
0
    private void OnGUI()
    {
        GUILayout.BeginVertical(GUILayout.Height(Screen.height));

        GUILayout.BeginHorizontal(GUILayout.Width(Screen.width));
        if (GUILayout.Button("Calibrate Straight", GUILayout.Height(60)))
        {
            _mStraight = _mFingerData;
            if (null != _mStraight)
            {
                PlayerPrefs.SetString(KEY_STRAIGHT, JsonUtility.ToJson(_mStraight));
            }
        }
        if (GUILayout.Button("Calibrate Fist", GUILayout.Height(60)))
        {
            _mFist = _mFingerData;
            if (null != _mFist)
            {
                PlayerPrefs.SetString(KEY_FIST, JsonUtility.ToJson(_mFist));
            }
        }
        GUILayout.EndHorizontal();

        GUILayout.FlexibleSpace();

        if (null != _mFingerData)
        {
            GUILayout.BeginHorizontal(GUILayout.Width(Screen.width));
            GUILayout.Label(string.Format("Thumb: {0}", _mFingerData.thumb));
            GUILayout.FlexibleSpace();
            GUILayout.EndHorizontal();

            GUILayout.BeginHorizontal(GUILayout.Width(Screen.width));
            GUILayout.Label(string.Format("Index: {0}", _mFingerData.index));
            GUILayout.FlexibleSpace();
            GUILayout.EndHorizontal();

            GUILayout.BeginHorizontal(GUILayout.Width(Screen.width));
            GUILayout.Label(string.Format("Middle: {0}", _mFingerData.middle));
            GUILayout.FlexibleSpace();
            GUILayout.EndHorizontal();

            GUILayout.BeginHorizontal(GUILayout.Width(Screen.width));
            GUILayout.Label(string.Format("Ring: {0}", _mFingerData.ring));
            GUILayout.FlexibleSpace();
            GUILayout.EndHorizontal();

            GUILayout.BeginHorizontal(GUILayout.Width(Screen.width));
            GUILayout.Label(string.Format("Pinky: {0}", _mFingerData.pinky));
            GUILayout.FlexibleSpace();
            GUILayout.EndHorizontal();
        }

        GUILayout.FlexibleSpace();
        GUILayout.EndVertical();
    }
Example #14
0
        private FingerData CreateFingerData(TouchData touch_data)
        {
            FingerData new_finger = new FingerData();

            new_finger.FingerId      = touch_data.FingerId;
            new_finger.StartPosition = touch_data.Position;
            new_finger.LastPosition  = touch_data.Position;

            return(new_finger);
        }
Example #15
0
 void SaveFingerData(int handIndex, Finger.FingerType fingerType, FingerData fingerData)
 {
     if (m_FingerDatas[handIndex].ContainsKey(fingerType))
     {
         m_FingerDatas[handIndex][fingerType] = fingerData;
     }
     else
     {
         m_FingerDatas[handIndex].Add(fingerType, fingerData);
     }
 }
Example #16
0
        public void OnStart(TouchData touch_data)
        {
            Debug.Log("DragStart");

            FingerData new_finger = new FingerData();

            new_finger.FingerId      = touch_data.FingerId;
            new_finger.StartPosition = touch_data.Position;
            new_finger.Position      = touch_data.Position;

            fingerList.Add(new_finger);
        }
    protected void Button2_Click(object sender, EventArgs e)
    {
        //////////////  initializing machine

        DeviceInfo deviceInfo = null;
        int        ret        = mfs100.Init();

        if (ret != 0)
        {
            Literal1.Text = mfs100.GetErrorMsg(ret).ToString();
        }
        else
        {
            deviceInfo = mfs100.GetDeviceInfo(); if (deviceInfo != null)
            {
                //string scannerInfo = "SERIAL NO.: " + deviceInfo.SerialNo + " MAKE: " + deviceInfo.Make + " MODEL: " + deviceInfo.Model; lblSerial.Text = scannerInfo;
            }
            else
            {
                //lblSerial.Text = "";
            }
            Literal1.Text = mfs100.GetErrorMsg(ret).ToString();
        }


        /////////////////// capturing finger
        FingerData fingerprintData = null;
        int        timeout         = 300000;
        string     datapath        = "c:\\fingerprints\\";
        int        ret1            = mfs100.AutoCapture(ref fingerprintData, timeout, false, false);

        if (ret1 != 0)
        {
            Literal1.Text = mfs100.GetErrorMsg(ret1).ToString();
        }
        else
        {
            string info = "Quality: " + fingerprintData.Quality.ToString() + "     Nfiq: " + fingerprintData.Nfiq.ToString() + "     Bpp: " + fingerprintData.Bpp.ToString() + "     GrayScale:" + fingerprintData.GrayScale.ToString() + "\nW(in):" + fingerprintData.InWidth.ToString() + "     H(in):" + fingerprintData.InHeight.ToString() + "     area(in):" + fingerprintData.InArea.ToString() + "     Dpi/Ppi:" + fingerprintData.Resolution.ToString() + "     Compress Ratio:" + fingerprintData.WSQCompressRatio.ToString();
            //lblStatus.Text = info;
            //b[count++] = fingerprintData.ISOTemplate;

            File.WriteAllBytes(datapath + "//ISOTemplate.iso", fingerprintData.ISOTemplate);
            File.WriteAllBytes(datapath + "//ISOImage.iso", fingerprintData.ISOImage);
            File.WriteAllBytes(datapath + "//AnsiTemplate.ansi", fingerprintData.ANSITemplate);
            File.WriteAllBytes(datapath + "//RawData.raw", fingerprintData.RawData);
            fingerprintData.FingerImage.Save(datapath + "//FingerImage.bmp", System.Drawing.Imaging.ImageFormat.Bmp);
            File.WriteAllBytes(datapath + "//WSQImage.wsq", fingerprintData.WSQImage);
            //ShowMessage("Capture Success.\nFinger data is saved at application path", false);
            Literal1.Text = "<script language='javascript'>window.alert('finger  captured');</script>";
        }

        //////////////////
    }
Example #18
0
        private bool BufferOutOfBounds(Vector2 lineA, Vector2 lineB, FingerData fingerData, int indexA, int indexB)
        {
            for (var i = indexA; i < indexB; i++)
            {
                if (Distance(lineA, lineB, fingerData.Buffer[i]) > 20.0f)
                {
                    return(true);
                }
            }

            return(false);
        }
 void Update()
 {
     if (Left_Hand_Skeleton != null)
     {
         fingerData = new FingerData(Left_Hand_Skeleton);
         Debug.Log(fingerData.ToString());
     }
     else
     {
         Debug.Log("No skeleton");
     }
 }
    public void onPinch(PointerEventData data, float delta)
    {
        tapStart = false;
        CameraController.inst.pinchMove(delta * 3);
        FingerData obj = getSameFinger(data);

        if (obj == null)
        {
            return;
        }

        obj.prePosition = data.position;
    }
Example #21
0
    /// <summary>
    /// 通过给定手指数据,判断是否处于伸手状态
    /// 当三个手指符合不包括拇指,判定为伸掌状态
    /// </summary>
    /// <param name="fingerData"></param>
    /// <param name="?"></param>
    bool OpenState(Dictionary <Finger.FingerType, FingerData> dic_FingersData, PointData palmData, out Vector dir, out Vector palmPos, out Vector palmDir)
    {
        bool isOpen = false;

        dir     = Vector.Zero;
        palmPos = Vector.Zero;
        palmDir = Vector.Zero;
        int count = 0;
        Dictionary <Finger.FingerType, FingerData> fingersOutThumb = new Dictionary <Finger.FingerType, FingerData>(dic_FingersData);

        fingersOutThumb.Remove(Finger.FingerType.TYPE_THUMB);

        var values = fingersOutThumb.Values;

        foreach (FingerData fingerData in values)
        {
            if (FingerMatch.StrightState(fingerData))
            {
                count++;
            }
        }
//		print ("FingerStright Count:"+count);
        if (count >= m_MatchNumber)
        {
            isOpen = true;
        }

        //指定输出的伸手方向为中指指向
        //如果没有识别中指,判定为false
        //如果中指不是伸直状态,判定为false
        if (fingersOutThumb.ContainsKey(Finger.FingerType.TYPE_MIDDLE))
        {
            FingerData middleFingerData = fingersOutThumb[Finger.FingerType.TYPE_MIDDLE];
            if (FingerMatch.StrightState(middleFingerData))
            {
                dir     = middleFingerData.m_Point.m_Direction;
                palmPos = palmData.m_Position;
                palmDir = palmData.m_Direction;
            }
            else
            {
                isOpen = false;
            }
        }
        else
        {
            isOpen = false;
        }

        return(isOpen);
    }
        private bool IsHeld(LeanFinger finger, FingerData fingerData)
        {
            if (IgnoreIsOverGui == true && finger.IsOverGui == true)
            {
                return(false);
            }

            if (RequiredSelectable != null && RequiredSelectable.IsSelected == false)
            {
                return(false);
            }

            return(fingerData.Eligible == true && finger.Age >= MinimumAge && finger.Set == true);
        }
        private FingerData GetFingerDataByRawCode(string raw_code)
        {
            string[] codePair = raw_code.Split(new string[] { ":" }, System.StringSplitOptions.None);

            if (codePair.Length == 2)
            {
                FingerData fingerData = new FingerData();
                fingerData.header = codePair[0];
                fingerData.index  = int.Parse(codePair[1]);
                return(fingerData);
            }

            return(default(FingerData));
        }
        protected override void LinkFingerUp(FingerData link)
        {
            // Calculate points
            var start = GetStartPoint(link.Finger);
            var end   = GetEndPoint(link.Finger, start);

            if (onReleasedFromTo != null)
            {
                onReleasedFromTo.Invoke(start, end);
            }

            if (onReleasedTo != null)
            {
                onReleasedTo.Invoke(end);
            }
        }
    /// <summary>
    /// 手指伸直的状态,当根骨-指尖的方向和指向的偏差小于阀值时,判定手指为伸直状态。
    /// 注意无效的方向为零向量,先判定是零向量
    /// </summary>
    /// <param name="adjustBorder">对阈值做的微调</param>
    /// <returns></returns>
    public static bool StrightState(FingerData fingerData, float adjustBorder=0f)
    {
        bool isStright =false;
        Vector disalDir = fingerData.m_Point.m_Direction;
        //如果指尖方向为0向量,表示无效的数据
        if (!disalDir.Equals(Vector.Zero))
        {
            Vector fingerDir = fingerData.m_Point.m_Position - fingerData.m_Position;//指尖位置减去指根位置,由指根指向指尖的向量
            float radian = fingerDir.AngleTo(disalDir);

            if (radian < FingerStrightState_Radian + adjustBorder)
            {
                isStright = true;
            }
        }
        return isStright;
    }
Example #26
0
    private void Awake()
    {
        if (instance != null)
        {
            Debug.LogError("There are multiple instances of " + typeof(TouchInput).ToString() + " present in the scene!");
            return;
        }

        instance = this;

        for (int i = 0; i < fingers.Length; i++)
        {
            fingers[i] = new FingerData();
        }

        InitInputDevice();
    }
Example #27
0
    // Start is called before the first frame update
    void Start()
    {
        hand     = GetComponent <OVRHand>();
        skeleton = GetComponent <OVRSkeleton>();
        fingers  = GetComponent <FingerData>();

        i_numBones = skeleton.Bones.Count;
        t_targets  = new Transform[i_numBones];
        for (int i = 0; i < i_numBones; i++)
        {
            t_targets[i] = skeleton.Bones[i].Transform;
        }

        f_pinchStrengths = new float[5];

        b_hasInitialized = true;
    }
    public void Initialize(int fingerId, FingerData data, HandController handController, FingerRaycaster fingerRaycaster)
    {
        if (_isInitialized)
        {
            return;
        }

        FingerId = fingerId;

        FingerData = data;

        HandController = handController;
        _raycaster     = fingerRaycaster;

        Set();

        _isInitialized = true;
    }
Example #29
0
    static readonly float FingerStrightState_Radian = Mathf.PI / 12;   //15度

    /// <summary>
    /// 手指伸直的状态,当根骨-指尖的方向和指向的偏差小于阀值时,判定手指为伸直状态。
    /// 注意无效的方向为零向量,先判定是零向量
    /// </summary>
    /// <param name="adjustBorder">对阈值做的微调</param>
    /// <returns></returns>
    public static bool StrightState(FingerData fingerData, float adjustBorder = 0f)
    {
        bool   isStright = false;
        Vector disalDir  = fingerData.m_Point.m_Direction;

        //如果指尖方向为0向量,表示无效的数据
        if (!disalDir.Equals(Vector.Zero))
        {
            Vector fingerDir = fingerData.m_Point.m_Position - fingerData.m_Position;            //指尖位置减去指根位置,由指根指向指尖的向量
            float  radian    = fingerDir.AngleTo(disalDir);

            if (radian < FingerStrightState_Radian + adjustBorder)
            {
                isStright = true;
            }
        }
        return(isStright);
    }
    //显示单个手指的数据
    //1.掌心到手指的连线-红色
    //2.手指的方向-蓝色
    void ShowFingerData(int handIndex, PointData palmData, FingerData fingerData)
    {
        Vector3 handPos = VectorTrans.ToUnityVector3(palmData.m_Position);
        Vector3 handDir = VectorTrans.ToUnityVector3(palmData.m_Direction);

        Vector3 fingerPos       = VectorTrans.ToUnityVector3(fingerData.m_Position);
        Vector3 fingerDistalPos = VectorTrans.ToUnityVector3(fingerData.m_Point.m_Position);
        Vector3 fingerDir       = VectorTrans.ToUnityVector3(fingerData.m_Point.m_Direction);

        Debug.DrawLine(handPos, fingerPos, Color.red);
        Debug.DrawLine(fingerPos, fingerDistalPos, Color.red);
        //手心到指尖的连线
        Debug.DrawLine(handPos, fingerDistalPos, Color.yellow);

        float vecLength = (fingerPos - fingerDistalPos).magnitude;

        Debug.DrawRay(fingerDistalPos, fingerDir * vecLength * 0.1f, Color.blue);
        Debug.DrawRay(handPos, handDir * vecLength * 0.1f, Color.blue);
    }
Example #31
0
    /// <summary>
    /// 判定一个手掌是否处于食指指向状态。
    /// 手掌中有matchNumber个手指满足即可,实际设定为2个。
    /// </summary>
    /// <param name="dic_FingersData"></param>
    /// <param name="matchNumber"></param>
    /// <param name="dir">【返回值】:如果匹配成功方向为掌心的方向</param>
    /// <returns>是否为食指指向状态。</returns>
    bool IndexPointState(Dictionary <Finger.FingerType, FingerData> dic_FingersData, out Vector dir)
    {
        bool isBend = false;

        dir = Vector.Zero;
        int count = 0;
        Dictionary <Finger.FingerType, FingerData> fingersOutThumbAndIndex = new Dictionary <Finger.FingerType, FingerData>(dic_FingersData);

        fingersOutThumbAndIndex.Remove(Finger.FingerType.TYPE_THUMB);

        //如果不存在食指的信息就不需要继续判断了
        if (fingersOutThumbAndIndex.ContainsKey(Finger.FingerType.TYPE_INDEX))
        {
            FingerData indexFinger = fingersOutThumbAndIndex[Finger.FingerType.TYPE_INDEX];
            //食指处于伸直状态才继续进行判断
            if (FingerMatch.StrightState(indexFinger))
            {
                fingersOutThumbAndIndex.Remove(Finger.FingerType.TYPE_INDEX);

                var values = fingersOutThumbAndIndex.Values;
                //遍历四指,匹配个数满足设定个数认定手掌为弯曲,并且设定弯曲的方向为掌心方向。
                foreach (FingerData fingerData in values)
                {
                    if (FingerMatch.BendState(fingerData))
                    {
                        count++;
                    }
                }

                //log
                //print("FingerPoint bend count:"+count);

                //判定弯曲手指的个数是否符合要求
                //判定食指是否是伸直状态
                if (count >= m_MatchNumber)
                {
                    isBend = true;
                    dir    = indexFinger.m_Point.m_Direction;//食指的方向
                }
            }
        }
        return(isBend);
    }
    static readonly float FingerStrightState_Radian = Mathf.PI/12; //15度

    #endregion Fields

    #region Methods

    //,out float eulerAugle)
    /// <summary>
    /// 判断一根手指是否处于弯曲状态
    /// </summary>
    /// <param name="fingerData">需要判定的手指数据</param>
    /// <param name="bandBorder">弯曲的阈值</param>
    /// <returns></returns>
    public static bool BendState(FingerData fingerData, float adjustBorder=0f)
    {
        bool isBend = false;

        //eulerAugle = -1f;
        Vector disalDir = fingerData.m_Point.m_Direction;
        if( !disalDir.Equals(Vector.Zero) )
        {
            Vector fingerDir = fingerData.m_Point.m_Position - fingerData.m_Position;//指尖位置减去指根位置,指跟到指尖的向量

            float radian = fingerDir.AngleTo(disalDir);
            //eulerAugle = radian*180/Mathf.PI;
            //夹角超过定义的阈值时,认定为弯曲状态
            if (radian > FingerBendState_Radian + adjustBorder)
            {
                isBend = true;
            }
        }

        return isBend;
    }
Example #33
0
 internal static pxcmStatus QueryFingerDataINT(IntPtr instance, FingerType fingerLabel, out FingerData fingerData)
 {
     fingerData = new FingerData();
     return PXCMHandData_IHand_QueryFingerData(instance, fingerLabel, fingerData);
 }
    /// <summary>
    /// 保存手的信息到指定的缓存中,也保存在当前数据中
    /// </summary>
    /// <param name="handIndex">Hand index.</param>
    /// <param name="hand">Hand.</param>
    /// <param name="curBufIndex">Current buffer index.</param>
    void SaveFingerDataWithHandIndex(Hand hand)
    {
        //做空判断好恶心,既然要求传入一个Hand,为什么你要传入一个null呢。
        //这里不做null的判断也不会有问题
        //if (hand != null)
        //{
        bool isLeft = hand.IsLeft;
        int handIndex = isLeft ? 0 : 1;

        foreach (Finger finger in hand.Fingers)
        {
            Finger.FingerType fingerType = finger.Type();

            Vector fingerDir = finger.Direction;

            // Bone bone = finger.Bone(Bone.BoneType.TYPE_DISTAL);
            // Vector distalPos = bone.Center;
            Vector distalPos = finger.TipPosition;
            //记录根骨位置
            Vector metacarpalPos = finger.Bone(Bone.BoneType.TYPE_METACARPAL).Center;

            //如果是拇指,用近端骨指的位置代替
            if (finger.Type()==Finger.FingerType.TYPE_THUMB)
            {
                metacarpalPos = finger.Bone(Bone.BoneType.TYPE_PROXIMAL).Center;
            }

            //将数据保存到m_FingerDatas中,以及buffer中。
            FingerData fingerData = new FingerData(distalPos,fingerDir, metacarpalPos);

            //Vector3 fingerPos = VectorTrans.ToUnityVector3(fingerData.m_Position);
            //s Vector3 fingerDistalPos = VectorTrans.ToUnityVector3(fingerData.m_Point.m_Position);
            SaveFingerData(handIndex, fingerType, fingerData);
        }
        //}
    }
    //显示单个手指的数据
    //1.掌心到手指的连线-红色
    //2.手指的方向-蓝色
    void ShowFingerData(int handIndex,PointData palmData,FingerData fingerData)
    {
        Vector3 handPos = VectorTrans.ToUnityVector3 (palmData.m_Position);
        Vector3 handDir = VectorTrans.ToUnityVector3 (palmData.m_Direction);

        Vector3 fingerPos = VectorTrans.ToUnityVector3 (fingerData.m_Position);
        Vector3 fingerDistalPos = VectorTrans.ToUnityVector3 (fingerData.m_Point.m_Position);
        Vector3 fingerDir = VectorTrans.ToUnityVector3 (fingerData.m_Point.m_Direction);

        Debug.DrawLine (handPos,fingerPos,Color.red);
        Debug.DrawLine(fingerPos, fingerDistalPos, Color.red);
        //手心到指尖的连线
        Debug.DrawLine(handPos, fingerDistalPos, Color.yellow);

        float vecLength = (fingerPos - fingerDistalPos).magnitude;
        Debug.DrawRay(fingerDistalPos, fingerDir * vecLength * 0.1f, Color.blue);
        Debug.DrawRay(handPos, handDir * vecLength * 0.1f, Color.blue);
    }
    // Update is called once per frame
    void Update()
    {
        #region INPUT
        #if !UNITY_ANDROID && !UNITY_IPHONE && !UNITY_BLACKBERRY && !UNITY_WINRT || UNITY_EDITOR
        //KeyBoard Input
        //IF MOVING RIGHT AND ON GROUND PLAY WALK ANIMATION OR IF MOVING LEFT AND ON GROUND PLAY WALK ANIMATION
        //OR IF NOT MOVING LEFT OR RIGHT NORMALIZEDHORIZONTALSPEED = 0
        if (UnityEngine.Input.GetKey(KeyCode.D) && _motor.motorState == PlatformerMotor2D.MotorState.OnGround && !_master._inSpear && !_master._isAttacking)
        {
            Move(1f);
        }
        else if (UnityEngine.Input.GetKey(KeyCode.A) && _motor.motorState == PlatformerMotor2D.MotorState.OnGround && !_master._inSpear && !_master._isAttacking)
        {
            Move(-1f);
        }
        else
        {
            Move(0f);
        }

        //IF PUSH SPACE THEN CALL THE JUMP FUNCTION
        if (UnityEngine.Input.GetKeyDown(KeyCode.Space) && _motor.motorState == PlatformerMotor2D.MotorState.OnGround)
        {
            Jump();
        }

        _motor.jumpingHeld = UnityEngine.Input.GetButton(PC2D.Input.JUMP);

        //IF PUSH CONTROL BUTTON THEN DASHDOWN
        if (UnityEngine.Input.GetKeyDown(KeyCode.S)&& Energy>=aerialCost)
        {
            Energy -= aerialCost;

            SaveEnergy();
            DashDown();
        }

        //IF PUSH CONTROL BUTTON THEN DASHDOWN
        if (UnityEngine.Input.GetButtonDown(PC2D.Input.DASH)&&Energy>=dashCost)
        {
            Energy -= dashCost;

            SaveEnergy();

            Dash();
        }

        //IF PUSH Z THEN CALL THE ATTACK FUNCTION
        if (UnityEngine.Input.GetKeyUp(KeyCode.Z) && _master._isAbleToAttack)
        {
            _AttackOne();
        }

        //IF PUSH X THEN CALL THE ATTACK FUNCTION
        if (UnityEngine.Input.GetKeyUp(KeyCode.X) && _master._isAbleToAttack)
        {
            _AttackTwo();
        }

        if (UnityEngine.Input.GetKey(KeyCode.Q) && _master._isAbleToThrowSpear)
        {
            HasSpears();
            if (hasSpears)
            {
                SpearState();
            }
        }
        else
        {
            CancelSpearState();
        }
        #else
        //if (!SspearControl.MobileSpearButtonPress || !AspearControl.MobileSpearButtonPress || !ATspearControl.MobileSpearButtonPress)
        //{
            //MOBILE SWIPE COTROLS

                    //VERTICAL SWIPE
            int fingerCount = 0;

            foreach (Touch touch in Input.touches)
            {
                if(touch.phase == TouchPhase.Began)
                {
                    initTouchPos = touch.position;
                }

                if (touch.phase != TouchPhase.Ended && touch.phase != TouchPhase.Canceled)
                {
                    fingerCount++;

                    if(fingerCount == 1 && touch.phase == TouchPhase.Moved || touch.phase == TouchPhase.Ended)
                    {
        //					if (initTouchPos.x > mid && touch.phase.x > mid)
        //					{
                            Vector2 touchFacing = (initTouchPos - touch.position).normalized;

                            if(Vector2.Dot(touchFacing, Vector2.up) > 0.8 && Vector2.Distance(initTouchPos, touch.position) > 50)
                            {
                                if (!_master._isGrounded)
                                {
                                    if(Energy>=aerialCost)
                                    {
                                        Energy -= aerialCost;
                                        SaveEnergy();
                                        DashDown();
                                    }
                                }
        //						else if (_controller.isGrounded)
        //							PA.RadialBlockAnim();
        //							//PA.RadialBlock();
                            }
        //					}
                    }
                }
            }

            //HORIZONTAL SWIPE CONTROLS 2.0 (ONLY ON RIGHT SIDE OF SCREEN)
            if (Input.touchCount == 0)
            {
                data.Clear();
            }
            else
            {
                foreach (Touch t in Input.touches)
                {
                    if (t.phase == TouchPhase.Began)
                    {
                        FingerData d = new FingerData(t.fingerId, t.position, Time.time);
                        data.Add (d);
                    }
                    else if (t.phase == TouchPhase.Ended)
                    {
                        int i = data.FindIndex (x => x.fingerID == t.fingerId);
                        if (i == -1)
                        {
                            Debug.Log ("No matching Begin");
                        }

                        if (i >= 0)
                        {
                            FingerData d = data[i];
                            data.RemoveAt(i);
                            float swipeDistHorizontal = (new Vector3(t.position.x,0, 0) - new Vector3(d.startPos.x, 0, 0)).magnitude;
        //						if (d.startPos.x < mid /*&& t.position.x < mid*/)
        //						{
        //							CannonScript cs = GetComponentInChildren<CannonScript>();
        //							Vector3 vel = GetForceFrom (t.position, /*ball.transform.position*/ cs.startPos.transform.position);
        //							angle = Mathf.Atan2 (vel.y, vel.x) * Mathf.Rad2Deg;
        //
        //							//float swipeValue  = Mathf.Sign(t.position.x - do.startPos.x);
        //
        ////							guiText.text = d.fingerID.ToString () + ": left side swipe";
        //
        //						}
                            if (swipeDistHorizontal > minSwipeDistX)
                            {
                                if (d.startPos.x >= mid && t.position.x >= mid)
                                {
                                    float swipeValue = Mathf.Sign(t.position.x - d.startPos.x);
                                    if (swipeValue > 0)
                                    {
                                        if (Energy>=dashCost)
                                        {
                                            Energy -= dashCost;
                                            SaveEnergy();
                                            MobileDash(right);
                                        }
                                        //RightSwipe
                                    }
                                    else if (swipeValue < 0)
                                    {
                                        if (Energy>=dashCost)
                                        {
                                            Energy -= dashCost;
                                            SaveEnergy();
                                            MobileDash(left);
                                        }
                                        //LeftSwipe
                                    }
            //							guiText.text = d.fingerID.ToString () + ": right side swipe";
                                }
                            }
        //						else
        //						{
        //							//guiText.text = d.fingerID.ToString () + ": overlap swipe";
        //						}
                        }
                    }
                }
            }
        //}

        #endif
        #endregion

        //MOVE
        _motor.normalizedXMovement = _master.normalizedHorizontalSpeed;

        if (Energy < MaxEnergy)
        {
            if (Energy <= 0f)
                Energy = 0f;

            Energy += Time.deltaTime * EnergyRegen;
            SaveEnergy();
        }

        if (Energy > MaxEnergy)
        {
            Energy = MaxEnergy;
            SaveEnergy();
        }
    }
    /// <summary>
    /// 保存指定的手指到指定的位置中
    /// </summary>
    /// <param name="handNumber">索引号 0表示左手</param>
    /// 
    /// <param name="finger">手指信息</param>
    void SaveFingerData(int handIndex,
                        Finger.FingerType fingerType,
				        FingerData fingerData)
    {
        //将data保存或者覆盖到m_FingerDatas中
        if(m_FingerDatas[handIndex].ContainsKey(fingerType))
        {
            m_FingerDatas[handIndex][fingerType] = fingerData;
        }
        else
        {
            m_FingerDatas[handIndex].Add(fingerType, fingerData);
        }

        //保存或者覆盖到buffer中
        if(m_FingerDatasBuffer[handIndex,m_CurBufIndex].ContainsKey(fingerType))
        {
            m_FingerDatasBuffer[handIndex, m_CurBufIndex][fingerType] = fingerData;
        }
        else
        {
            m_FingerDatasBuffer[handIndex, m_CurBufIndex].Add(fingerType, fingerData);
        }
    }
Example #38
0
            /** 
                 @brief Return the data of the requested finger
                 @note This information is available only in full-hand tracking mode (TRACKING_MODE_FULL_HAND)
                 @see PXCHandConfiguration::SetTrackingMode
			
                 @param[in] fingerLabel - the ID of the requested finger.
                 @param[out] fingerData - the tracking data of the requested finger.
			
                 @return PXCM_STATUS_NO_ERROR - operation succeeded.
			
                 @see FingerType
                 @see FingerData
             */
            public pxcmStatus QueryFingerData(FingerType fingerLabel, out FingerData fingerData)
            {
                return QueryFingerDataINT(instance, fingerLabel, out fingerData);
            }
 public void Set(FingerData fd)
 {
     m_Point = fd.m_Point;
     m_Position = fd.m_Position;
 }