Ejemplo n.º 1
0
    protected float GetInputZoom()
    {
        // Get the fingers we want to use
        var fingers = Use.GetFingers();

        //ignore zoom with scrollwheel if over ui
        if (fingers.Count == 0 && LeanTouch.PointOverGui(Input.mousePosition))
        {
            return(0);
        }

        // Get current point and previous point
        var lastScreenPoint = Lean.Touch.LeanGesture.GetLastScreenCenter(fingers);
        var screenPoint     = Lean.Touch.LeanGesture.GetScreenCenter(fingers);

        var pinchScale = Lean.Touch.LeanGesture.GetPinchScale(fingers, -ZoomSensitivity * 0.04f);

        return((1 - Mathf.Clamp(pinchScale, 0, 2)) * ZoomSensitivity);
    }
Ejemplo n.º 2
0
    protected virtual void Translate(Vector2 screenDelta)
    {
        // Make sure the camera exists
        var camera = LeanTouch.GetCamera(Camera, gameObject);

        if (camera == null)
        {
            return;
        }

        // Screen position of the transform
        var screenPosition = camera.WorldToScreenPoint(transform.position);

        // Add the deltaPosition
        screenPosition += (Vector3)screenDelta;

        // Perform the translation
        transform.position = camera.ScreenToWorldPoint(screenPosition);
    }
Ejemplo n.º 3
0
    protected virtual void Update()
    {
        // If we require a selectable and it isn't selected, cancel translation
        //			if ((RequiredSelectable != null && RequiredSelectable.IsSelected == false) && !ModelManager._instance)
        //			{
        //				return;
        //			}
        if ((RequiredSelectable != null && RequiredSelectable.IsSelected == false))
        {
            return;
        }
        // Get the fingers we want to use
        var fingers = LeanTouch.GetFingers(IgnoreGuiFingers, RequiredFingerCount);

        // Calculate the screenDelta value based on these fingers
        var screenDelta = LeanGesture.GetScreenDelta(fingers);

        // Perform the translation
        Translate(screenDelta);
    }
Ejemplo n.º 4
0
        private void DrawFingers(LeanTouch touch)
        {
            EditorGUILayout.LabelField(new GUIContent("Fingers", "Index - State - Taps - X, Y - Age"), EditorStyles.boldLabel);

            allFingers.Clear();
            allFingers.AddRange(LeanTouch.Fingers);
            allFingers.AddRange(LeanTouch.InactiveFingers);
            allFingers.Sort((a, b) => a.Index.CompareTo(b.Index));

            for (var i = 0; i < allFingers.Count; i++)
            {
                var finger   = allFingers[i];
                var progress = touch.TapThreshold > 0.0f ? finger.Age / touch.TapThreshold : 0.0f;
                var style    = GetFadingLabel(finger.Set, progress);

                if (style.normal.textColor.a > 0.0f)
                {
                    var screenPosition = finger.ScreenPosition;
                    var state          = "UPDATE";

                    if (finger.Down == true)
                    {
                        state = "DOWN";
                    }
                    if (finger.Up == true)
                    {
                        state = "UP";
                    }
                    if (finger.IsActive == false)
                    {
                        state = "INACTIVE";
                    }
                    if (finger.Expired == true)
                    {
                        state = "EXPIRED";
                    }

                    EditorGUILayout.LabelField(finger.Index + " - " + state + " - " + finger.TapCount + "  + " + Mathf.FloorToInt(screenPosition.x) + ", " + Mathf.FloorToInt(screenPosition.y) + ") - " + finger.Age.ToString("0.0"), style);
                }
            }
        }
Ejemplo n.º 5
0
    private void Rotate(Vector3 center, float degrees)
    {
        if (Relative == true)
        {
            // Make sure the camera exists
            var camera = LeanTouch.GetCamera(Camera, gameObject);

            if (camera != null)
            {
                // World position of the reference point
                var worldReferencePoint = camera.ScreenToWorldPoint(center);

                // Rotate the transform around the world reference point
                transform.RotateAround(worldReferencePoint, camera.transform.forward, degrees);
            }
        }
        else
        {
            transform.rotation *= Quaternion.AngleAxis(degrees, RotateAxis);
        }
    }
Ejemplo n.º 6
0
    protected override void Translate(Vector2 screenDelta)
    {
        // Make sure the camera exists
        var camera = LeanTouch.GetCamera(Camera, gameObject);

        if (camera != null)
        {
            // Screen position of the transform
            var screenPoint = camera.WorldToScreenPoint(transform.position);

            // Add the deltaPosition
            screenPoint += (Vector3)screenDelta;

            Vector3 pos         = transform.position;
            Vector3 targetPoint = camera.ScreenToWorldPoint(screenPoint);

            if (Mathf.Abs(moveForward.Direction.z) > 0.5f)
            {
                pos.x = targetPoint.x;
                if (!InRange(pos.x, moveForward.CenterPoint.x))
                {
                    return;
                }
            }
            else if (Mathf.Abs(moveForward.Direction.x) > 0.5f)
            {
                pos.z = targetPoint.z;
                if (!InRange(pos.z, moveForward.CenterPoint.z))
                {
                    return;
                }
            }

            transform.position = pos;
        }
        else
        {
            Debug.LogError("Failed to find camera. Either tag your camera as MainCamera, or set one in this component.", this);
        }
    }
        public void Initialize()
        {
            registeredSwipeDeltaCallbacks = new Dictionary <GameObject, List <OnTouchDelegate> >();
            registeredTapCallbacks        = new Dictionary <LeanFingerTap, List <OnTouchDelegate> >();

            leanTouch      = gameObject.AddComponent <LeanTouch>();
            leanSelect     = gameObject.AddComponent <LeanSelect>();
            leanFingerTap  = gameObject.AddComponent <LeanFingerTap>();
            leanFingerDown = gameObject.AddComponent <LeanFingerDown>();
            leanFingerUp   = gameObject.AddComponent <LeanFingerUp>();

            leanFingerTap.OnFinger.AddListener(leanSelect.SelectScreenPosition);
            leanFingerDown.OnFinger.AddListener(leanSelect.SelectScreenPosition);

            leanSelect.LayerMask     &= ~(1 << LayerMask.NameToLayer("PostProcessing"));
            leanSelect.SelectUsing    = LeanSelect.SelectType.CanvasUI;
            leanSelect.SelectUsingAlt = LeanSelect.SelectType.Raycast3D;

            leanFingerDown.IgnoreStartedOverGui = false;
            leanFingerUp.IgnoreStartedOverGui   = false;
            leanFingerTap.IgnoreStartedOverGui  = false;
        }
    protected virtual void Update()
    {
        // If we require a selectable and it isn't selected, cancel translation
        if (RequiredSelectable != null && RequiredSelectable.IsSelected == false)
        {
            return;
        }

        // Get the fingers we want to use
        var fingers = LeanTouch.GetFingers(IgnoreGuiFingers, RequiredFingerCount, RequiredSelectable);

        // Calculate the screenDelta value based on these fingers
        var screenDelta = LeanGesture.GetScreenDelta(fingers);

        //Swipe Left or Right
        if (screenDelta.x < -Mathf.Abs(screenDelta.y) || screenDelta.x > Mathf.Abs(screenDelta.y))
        {
            Translate(screenDelta);
        }

        // Perform the translation
        //sTranslate(screenDelta);
    }
Ejemplo n.º 9
0
        private void DrawFingers(LeanTouch touch)
        {
            EditorGUILayout.LabelField("Fingers", EditorStyles.boldLabel);

            allFingers.Clear();
            allFingers.AddRange(LeanTouch.Fingers);
            allFingers.AddRange(LeanTouch.InactiveFingers);
            allFingers.Sort((a, b) => a.Index.CompareTo(b.Index));

            for (var i = 0; i < allFingers.Count; i++)
            {
                var finger   = allFingers[i];
                var progress = touch.TapThreshold > 0.0f ? finger.Age / touch.TapThreshold : 0.0f;
                var style    = GetFadingLabel(finger.Set, progress);

                if (style.normal.textColor.a > 0.0f)
                {
                    var screenPosition = finger.ScreenPosition;

                    EditorGUILayout.LabelField("#" + finger.Index + " x " + finger.TapCount + " (" + Mathf.FloorToInt(screenPosition.x) + ", " + Mathf.FloorToInt(screenPosition.y) + ") - " + finger.Age.ToString("0.0"), style);
                }
            }
        }
Ejemplo n.º 10
0
        private bool Scale()
        {
            // Get the fingers we want to use
            var fingers = LeanTouch.GetFingers(_ignoreGuiFingers, 2);

            // Calculate the scaling values based on these fingers
            var scale = LeanGesture.GetPinchScale(fingers, 0);

            if (scale == 1)
            {
                return(false);
            }
            float newScale = _camera.fieldOfView / scale;

            newScale            = Mathf.Clamp(newScale, 5, _maxFoV);
            _camera.fieldOfView = newScale;

            var degrees = LeanGesture.GetTwistDegrees(fingers);

            _transform.RotateAround(_transform.position, Vector3.forward, degrees);

            return(true);
        }
Ejemplo n.º 11
0
    protected virtual void LateUpdate()
    {
        var fingers = LeanTouch.GetFingers(false, false, 1);

        if (fingers.Count < 1)
        {
            return;
        }

        var lastScreenPoint = LeanGesture.GetLastScreenCenter(fingers);
        var screenPoint     = LeanGesture.GetScreenCenter(fingers);

        var worldDelta = lastScreenPoint - screenPoint;

        if (worldDelta.x < 0)
        {
            MoveLeft(Mathf.Abs(worldDelta.x));
        }
        else if (worldDelta.x > 0)
        {
            MoveRight(Mathf.Abs(worldDelta.x));
        }
        Shoot();
    }
Ejemplo n.º 12
0
        private void DrawSettings(LeanTouch touch)
        {
            DrawDefault("TapThreshold");
            DrawDefault("SwipeThreshold");
#if LEAN_ALLOW_RECLAIM
            DrawDefault("ReclaimThreshold");
#endif
            DrawDefault("ReferenceDpi");
            DrawDefault("GuiLayers");

            EditorGUILayout.Separator();

            DrawDefault("RecordFingers");

            if (touch.RecordFingers == true)
            {
                EditorGUI.indentLevel++;
                DrawDefault("RecordThreshold");
                DrawDefault("RecordLimit");
                EditorGUI.indentLevel--;
            }

            EditorGUILayout.Separator();

            DrawDefault("SimulateMultiFingers");

            if (touch.SimulateMultiFingers == true)
            {
                EditorGUI.indentLevel++;
                DrawDefault("PinchTwistKey");
                DrawDefault("MovePivotKey");
                DrawDefault("MultiDragKey");
                DrawDefault("FingerTexture");
                EditorGUI.indentLevel--;
            }
        }
Ejemplo n.º 13
0
    protected virtual void Update()
    {
        // If we require a selectable and it isn't selected, cancel the translation
        if (RequiredSelectable != null && RequiredSelectable.IsSelected == false)
        {
            return;
        }

        // Obtain the fingers we want to use
        var fingers = LeanTouch.GetFingers(IgnoreGuiFingers, RequiredFingerCount, RequiredSelectable);

        // Calculate the screenDelta value based on these fingers
        var screenDelta = LeanGesture.GetScreenDelta(fingers);

        // Calculate the rotation values based on these fingers
        var center  = LeanGesture.GetScreenCenter(fingers);
        var degrees = LeanGesture.GetTwistDegrees(fingers);

        // Perform the rotation
        Rotate(center, degrees);

        // Perform the translation
        Translate(screenDelta);
    }
Ejemplo n.º 14
0
    protected override void Update()
    {
        base.Update();
        ShowMessage("Fire", "Fire : " + Convert.ToInt32(IsFiring));
        ShowMessage("Scope", "Toggle Scope : " + Convert.ToInt32(ViewingScope));
        ShowMessage("Reloading", "Is Reloading: " + Convert.ToInt32(isReloading));
        ShowMessage("MiniReloading", "Is Adjusting Root: " + Convert.ToInt32(isMiniReloading));

        ShowMessage("Ducking", "Is Ducking: " + Convert.ToInt32(isDucking));

        txtReload.text = "Ammo: " + currentAmmo + "/" + AmmoPerClip;

        UpdateHealth();


        string zm = string.Format("X{0:0}", GetZoomFrom(6, 20));

        txtZoom.text = zm;

        if (IsUserControllable)
        {
            RotationControls(false);

            //Zoom Controls
            List <LeanFinger> fingers = LeanTouch.GetFingers(false);

            Vector3[] corners = new Vector3[4];
            ScopeUICenter.transform.GetChild(0).GetComponent <RectTransform>().GetWorldCorners(corners);
            Vector3 pivot = corners[0];
            for (int i = 0; i < fingers.Count; i++)
            {
                if (fingers[i].LastScreenPosition.x <= corners[0].x)
                {
                    fingers.RemoveAt(i);
                    i--;
                }
            }


            if (fingers.Count > 0)
            {
                if (isDraggingZoom)
                {
                    Vector2 delta = LeanGesture.GetScreenDelta(fingers) * ZoomSpeed * Time.deltaTime;
                    ScopeCamera.fieldOfView += delta.y;
                    ScopeCamera.fieldOfView  = Mathf.Clamp(ScopeCamera.fieldOfView, MinZoom, MaxZoom);


                    //For 60 degrees of rotation
                    float zRot;
                    if (SniperPrimaryHand == PrimaryHand.RightHanded)
                    {
                        zRot = -Zoom * .6f;
                    }
                    else
                    {
                        zRot = Zoom * .6f;
                    }
                    //Also adjust the progress bar
                    Transform scopeCenter = ScopeUICenter.transform;
                    scopeCenter.localEulerAngles = new Vector3(scopeCenter.localEulerAngles.x, scopeCenter.localEulerAngles.y, zRot);
                }
            }

            if (animatingReticule)
            {
                rTime += Time.deltaTime * ReticuleOscillationSpeed;

                float osc = Mathf.PingPong(rTime, .25f) + 1;
                CurrentSniperPanel.transform.GetChild(0).transform.localScale = new Vector3(osc, osc, osc);

                if (rTime >= .5f)
                {
                    animatingReticule = false;
                    rTime             = 0;
                }
            }
        }
    }
Ejemplo n.º 15
0
 public void OnAwake(MonoBehaviour monoBehaviour)
 {
     leanTouch     = monoBehaviour.transform.Find("LeanTouch").GetComponent <LeanTouch>();
     leanSelect    = monoBehaviour.transform.Find("LeanTouch").GetComponent <LeanSelect>();
     leanFingerTap = monoBehaviour.transform.Find("LeanTouch").GetComponent <LeanFingerTap>();
 }
Ejemplo n.º 16
0
    protected virtual void LateUpdate()
    {
        // Make sure the camera exists
        if (LeanTouch.GetCamera(ref cameraMain, gameObject) == true)
        {
            // Get the fingers we want to use
            var fingers = LeanTouch.GetFingers(IgnoreGuiFingers, RequiredFingerCount);
            //return;

//            if (fingers.Count == 0)
//            {
//                return;
//            }

            //单指操作
            if (fingers.Count == 1)
            {
                if (bDisableAll)
                {
                    return;
                }


                Vector2 screenDelta = LeanGesture.GetScreenDelta(fingers);

                if (!bIsMove && !bMouseRightDown)                 //鼠标右键按下时,不能平移
                {
                    if (Input.GetMouseButtonDown(0))
                    {
                        _cameraDest = GetCenterDistance();
                    }

                    CameraPan(screenDelta);
                }

                //鼠标右键按下时上下调整视角,左右绕中心旋转
                MouseRightUpdate();

//				if (Input.GetMouseButton (1)) {
//					MouseRightTour ();
//				}
            }

            //双指pinch捏放,缩放操作
            float pinchRatio = LeanGesture.GetPinchRatio(fingers, WheelSensitivity); //捏放比例

            //判断pinchRatio是否为1,1表示没有缩放
            if (pinchRatio != 1.0f)
            {
                CameraDistanceRatio(pinchRatio);                 //换为z轴方向移动
            }

            //双指操作
            if (fingers.Count == 2)
            {
                //双指上下移动,调整仰角
                Vector2 heightDelta = LeanGesture.GetScreenDelta(fingers); //手指移动的屏幕距离

                //双指Twist旋转,绕屏幕中心与地面交点旋转
                float twistDegree = LeanGesture.GetTwistDegrees(fingers, LeanGesture.GetScreenCenter(), LeanGesture.GetLastScreenCenter());

                //双指操作
                CameraTwistAndHeight(heightDelta.y, twistDegree);

                //双指操作,调整仰角,绕屏幕中心与地面交点旋转(双指旋转时不符合功能,弃用)
                //计算屏幕中心点
//				Vector3 centerPoint;
//				float enter;
//				if (GetInterPoint(cameraMain, new Vector3(0.5F, 0.5F, 0), out centerPoint, out enter))
//				{
//					_cameraDest = enter + 0.3f;
//
//					CameraTAndH(centerPoint, heightDelta.y, twistDegree);
//				}
            }
        }
    }
Ejemplo n.º 17
0
    // Update is called once per frame
    protected virtual void Update()
    {
        //Transition animation between views
        if (isTransitioningViews)
        {
            //Set target position
            Vector3 target = ViewingScope ? ScopeLocation.position : StandardLocation.position;

            //Lerp to the new position
            time += Time.deltaTime * ScopeTransitionSpeed;

            Camera.transform.position = Vector3.Lerp(Camera.transform.position, target, time);

            if (time >= .2f && !calledBeginTransition)
            {
                OnFinishedScopeTransition();
                ScopeParent.SetActive(ViewingScope);
                calledBeginTransition = true;
            }

            if (time >= .5f && !calledMiddleTransition)
            {
                OnFinishedScopeTransitionMiddle();
                calledMiddleTransition = true;
            }

            if (time >= .8f && !calledEndTransition)
            {
                OnFinishedScopeTransitionLate();
                calledEndTransition = true;
            }


            if (time >= 1)
            {
                isTransitioningViews = false;
                IsUserControllable   = wasUserControllable;
            }
        }

        //Affect children too
        foreach (Transform child in ScopeCamera.transform)
        {
            child.GetComponent <Camera>().fieldOfView = ScopeCamera.fieldOfView;
        }


        List <LeanFinger> fingers = LeanTouch.GetFingers(false);

        //Used for ZoomPinch
        if (fingers.Count == 1)
        {
            timeSingle += Time.deltaTime;
        }
        if (fingers.Count == 0)
        {
            timeSingle = 0;
        }


        //Recoil
        if (isRecoiling)
        {
            recoilTime += Time.deltaTime;
            float delta     = 0;
            float upDivisor = 20.0f;
            //Quickly move up
            if (recoilTime < recoilDuration / upDivisor)
            {
                delta = -currentRecoilSpeed * upDivisor;
            }
            //Slowly move back down
            else if (recoilTime < recoilDuration)
            {
                delta = currentRecoilSpeed * (upDivisor / (upDivisor - 1));
            }
            else
            {
                isRecoiling = false;
                recoilTime  = 0;
            }
            if (ViewingScope)
            {
                //To Adjust for zoom
                delta *= InvZoom(Zoom, MinimumRotationModifier * 2);
            }


            xRot += delta;
        }
    }
Ejemplo n.º 18
0
    protected override void Update()
    {
        base.Update();


        ShowMessage("CameraAngle", "Camera Angle : " + CameraRotation.ToString());
        ShowMessage("Scope", "Toggle Scope : " + Convert.ToInt32(ViewingScope));
        ShowMessage("Fire", "Fire : " + Convert.ToInt32(IsFiring));
        ShowMessage("Reloading", "Is Reloading: " + Convert.ToInt32(isReloading));
        ShowMessage("MiniReloading", "Is Reloading While In Scope: " + Convert.ToInt32(isMiniReloading));

        ShowMessage("Supercharged", "Supercharged : " + Convert.ToInt32(isSupercharged));

        txtReload.text = string.Format("{0:00}", currentAmmo);

        UpdateHealth();
        RotationControls();

        if (IsUserControllable)
        {
            bool prevPanning = panning;

            List <LeanFinger> fingers = LeanTouch.GetFingers(false);

            if (fingers.Count > 0)
            {
                if (canSwitch)
                {
                    Ray        ray = fingers[0].GetRay();
                    RaycastHit hit = default(RaycastHit);
                    if (isDraggingZoom && ViewingScope)
                    {
                        panning   = false;
                        canSwitch = false;
                    }
                    else
                    {
                        panning = true;
                    }
                }
                if (!panning)
                {
                    Vector2 delta = LeanGesture.GetScreenDelta(fingers) * ZoomSpeed * Time.deltaTime;
                    ScopeCamera.fieldOfView -= delta.y;
                    ScopeCamera.fieldOfView  = Mathf.Clamp(ScopeCamera.fieldOfView, MinZoom, MaxZoom);


                    //For 60 degrees of rotation
                    float zRot;
                    if (SniperPrimaryHand == PrimaryHand.RightHanded)
                    {
                        zRot = Zoom * .6f;
                    }
                    else
                    {
                        zRot = -Zoom * .6f;
                    }
                    //Also adjust the progress bar
                    Transform scopeCenter = ScopeUICenter.transform;
                    scopeCenter.localEulerAngles = new Vector3(scopeCenter.localEulerAngles.x, scopeCenter.localEulerAngles.y, zRot);
                }
            }

            //Powerups Update
            if (isRechargingHealth)
            {
                Health += Time.deltaTime * HealthRegenSpeed;
                //No need to clamp - handled by UpdateHealth
            }


            string zm = string.Format("X{0:00}", GetZoomFrom(0, 4));
            txtZoom.text = zm;
        }
    }
Ejemplo n.º 19
0
    protected override void RotationControls(bool ignoreGUI = true, bool linear = false)
    {
        if (isZooming)
        {
            return;
        }

        //For smooth rotation
        Vector3 prevEuler = new Vector3(xRot, yRot, 0);

        List <LeanFinger> fingers = LeanTouch.GetFingers(true);

        float sens = RotationSensitivity;

        if (ViewingScope)
        {
            if (Zoom != 0)
            {
                sens = RotationSensitivity * InvZoom(Zoom, .25f);
            }
            else
            {
                sens = RotationSensitivity;
            }
        }



        //Change in finger position (sliding)
        Vector2 delta = LeanGesture.GetScreenDelta(fingers) * sens;

        //For the x rotation, we don't use the Camera's euler angles directly.
        //We initialize xRot to zero before this method (since we're using localEulerAngles), then we constanly subtract delta.y
        //Then we clamp that independent value, and apply to the localEulerAngles.
        //Inspired from joel_b on http://answers.unity3d.com/questions/18680/limiting-rotation-of-an-object.html

        if (panning)
        {
            xRot -= delta.y;
            yRot += delta.x;
        }


        if (RestrictXRotation)
        {
            xRot = WrapAngle(Mathf.Clamp(xRot, MinXRotation, MaxXRotation));
        }
        if (RestrictYRotation)
        {
            yRot = WrapAngle(Mathf.Clamp(yRot, MinYRotation, MaxYRotation));
        }


        //
        //Root.transform.rotation = Quaternion.Euler();

        if (ExtraSmooth)
        {
            Quaternion look = Quaternion.Euler(new Vector3(xRot, yRot, 0));
            if (RotationSmooth != -1)
            {
                Root.rotation = Quaternion.Slerp(Root.rotation, look, RotationSmooth);
            }
            else
            {
                Root.rotation = Quaternion.Slerp(Root.rotation, look, RotationSensitivity);
            }
        }
        else
        {
            if (RotationSmooth != -1)
            {
                Root.transform.eulerAngles = Vector3.Lerp(prevEuler, new Vector3(xRot, yRot, 0), RotationSmooth);
            }
            else
            {
                Root.transform.eulerAngles = Vector3.Lerp(prevEuler, new Vector3(xRot, yRot, 0), RotationSensitivity);
            }
        }



        ShowMessage("CameraAngle", "Camera Angle : " + CameraRotation.ToString());
    }
Ejemplo n.º 20
0
        private void OnTrackingLost()
        {
            ModelManager._instance.offCardModelIsMoving = false;
            ModelManager._instance.currentModelisMoving = false;
            //EventManager.StopListening ("OffCard", offCardListener);
            if (ModelManager._instance.isOffCard && modelIsOffCard)
            {
                if (LeanTouch.GetCamera(ref camera1) == true)
                {
                    //float dis = go.transform.position.z - camera1.transform.position.z; //计算与相机之间的距离,确定z = 多少
                    ModelManager._instance.ModelCountMinusOne();
                    Vector3 position = new Vector3(Screen.width / 2, Screen.height / 2, zAxisDistance);                  // 经调试,这里Z直接设置成20,显示在屏幕中的模型大小比较合适
                    position = camera1.ScreenToWorldPoint(position);
                    ModelManager._instance.offCardModelTransform.position = position;
                    Animator animator2 = ModelManager._instance.offCardModelTransform.GetComponent <Animator> ();
                    if (animator2)
                    {
                        animator2.Play("Take 001");
                    }
                    //go.transform.localRotation = modelOriginQua;
                    //这个角度的模型脱卡后稍微好看一点
                    //Utility.offCardModelTransform.localRotation = Quaternion.Euler(new Vector3(-29,-29,8));
                    //Utility.offCardModelTransform.localRotation = Quaternion.Euler(new Vector3(29,151,-8));
                    return;
                }
            }
            for (int i = 0; i < this.transform.childCount; i++)
            {
                Utility.HideRendererAndCollider(this.transform.GetChild(i));
            }

            Animator animator = GetComponentInChildren <Animator> ();

            if (animator)
            {
                animator.Play("Take 001");
                //animator.Stop();
//				ParticleSystem tapParticle = GetTypeParticle (this.transform.GetChild (0),"Tap_Particle");
//				ParticleSystem foundParticle = GetTypeParticle (this.transform.GetChild (0),"Found_Particle");
//				if (tapParticle)	{	tapParticle.Stop ();	}
//				if (foundParticle)	{	foundParticle.Stop ();	}
            }
            if (this.transform.childCount > 0)
            {
                ParticleControl(false, "Found_Particle", this.transform.GetChild(0));
            }

            lostCount++;
            if (lostCount > 2)
            {
                if (ModelManager._instance.isOffCard)
                {
                    EventManager.StartListening("RecoveryModelToTarget", recoveryModelListener);
                }
                //刚加载识别图的时候,总是会先执行Lost方法两次,所以,两次之后再执行脱卡的方法,估计还得改
                ModelManager._instance.ModelCountMinusOne();                 // lost之后,found数目-1

                if (ModelManager._instance.modelCount == 0 && ModelManager._instance.currentRotationTransform)
                {
                    //ModelManager._instance.currentRotationTransform = null;
                    //ModelManager._instance.currentModelisMoving = false;
                    Utility.PrepareForSendMessage("FoundTarget", "0");
                }
            }
            Debug.Log("Trackable " + mTrackableBehaviour.TrackableName + " -------------------------------- lost");
        }
Ejemplo n.º 21
0
        private void OnTrackingFound()
        {
            if (ModelManager._instance.isOffCard && modelIsOffCard)
            {
                Debug.Log("handle reFound");
                ModelManager._instance.offCardModelIsMoving = false;
                if (LeanTouch.GetCamera(ref camera1) == true)
                {
                    ModelManager._instance.ModelCountPlusOne();                                         //发现的模型数目+1
                    //float dis = go.transform.position.z - camera1.transform.position.z; //计算与相机之间的距离,确定z = 多少
                    Vector3 position = new Vector3(Screen.width / 2, Screen.height / 2, zAxisDistance); // 经调试,这里Z直接设置成20,显示在屏幕中的模型大小比较合适
                    position = camera1.ScreenToWorldPoint(position);
                    ModelManager._instance.offCardModelTransform.position = position;
                    //go.transform.localRotation = modelOriginQua;
                    //这个角度的模型脱卡后稍微好看一点
                    //Utility.offCardModelTransform.localRotation = Quaternion.Euler(new Vector3(-29,-29,8));
                    ModelManager._instance.offCardModelTransform.localRotation = Quaternion.Euler(new Vector3(29, 151, -8));
                    return;
                }                                               //return;
            }

            if (!isModelLoaded)
            {             //if no model bind
                StartCoroutine(LoadModel());
            }
            ModelManager._instance.ModelCountPlusOne();            //发现的模型数目+1
            if (ModelManager._instance.modelCount == 1)
            {
                Utility.PrepareForSendMessage("FoundTarget", "1");
            }
            else
            {
                Debug.Log("----current model count ----" + ModelManager._instance.modelCount);
            }
            if (ModelManager._instance.isOffCard)
            {
                EventManager.StopListening("RecoveryModelToTarget", recoveryModelListener);
                EventManager.TriggerEvent("RecoveryModelToTarget");                 //还原其他模型到target。因为脱卡只留一个模型
            }
            //RecoveryModelToTarget();
            if (this.transform.childCount >= 1)
            {
                //show the first child transform
                Transform foundTransform = this.transform.GetChild(0);
                if (isFirstFound)
                {
                    EventManager.StartListening("OffCard", offCardListener);
                    //这行代码是方便测试用的,正式使用应该要用LoadModel方法中的。
                    AssMemoryManager.AddGOToMemoryManager(mTrackableBehaviour.TrackableName, this.gameObject);
                    //这里记录初始位置,便于以后各种手势之后可以恢复原来的状态。第一次found的时候肯定是初始状态了
                    modelOriginLocalPos = foundTransform.localPosition;
                    modelOriginLocalQua = foundTransform.localRotation;
                    modelOriginPos      = foundTransform.position;
                    modelOriginQua      = foundTransform.rotation;
                    modelOriginScale    = foundTransform.localScale;
                    isFirstFound        = false;
                }
                else
                {
                    foundTransform.localPosition = modelOriginLocalPos;
                    foundTransform.localRotation = modelOriginLocalQua;
                    foundTransform.localScale    = modelOriginScale;
                }
                Utility.ShowRendererAndCollider(foundTransform);
                //ParticleSystem foundParticle = GetTypeParticle (foundTransform, "Found_Particle");
                Animator            animator        = GetComponentInChildren <Animator> ();
                LeanRotationControl rotationControl = GetComponentInChildren <LeanRotationControl> ();
                if (rotationControl)
                {
                    rotationControl.enabled = true;
                }
                //if (foundParticle)		{	foundParticle.Play ();			}
                if (animator)
                {
                    animator.Play("Take 001", 0, 0);
                }
                ParticleControl(true, "Found_Particle", this.transform.GetChild(0));

                if (!ModelManager._instance.isOffCard)
                {
                    ModelManager._instance.currentRotationTransform = this.transform.GetChild(0);
                }
            }
            else
            {
                Debug.Log("child count is 0");
            }
            //每次扫描过后,更新model的Index值,后面AssMemoryManager会根据这个值来管理这些模型
            //AssMemoryManager.UpdateModelIndex(mTrackableBehaviour.TrackableName);
            if (ModelManager._instance.isOffCard)
            {
                EventManager.TriggerEvent("OffCard");
            }

            Debug.Log("Trackable " + mTrackableBehaviour.TrackableName + " --------------------------------  found");
        }
Ejemplo n.º 22
0
    protected override void OnUpdate()
    {
        var localPlayerId = GetSingleton <NetworkIdComponent>().Value;
        var localInput    = GetSingleton <CommandTargetComponent>().targetEntity;

        if (localInput == Entity.Null)
        {
            Entities.WithNone <PlayerInput>().ForEach((Entity ent, ref Player player) =>
            {
                if (player.PlayerId == localPlayerId)
                {
                    PostUpdateCommands.AddBuffer <PlayerInput>(ent);
                    PostUpdateCommands.SetComponent(GetSingletonEntity <CommandTargetComponent>(), new CommandTargetComponent {
                        targetEntity = ent
                    });
                }
            });
            return;
        }

        var input = default(PlayerInput);

        input.tick = World.GetExistingSystem <ClientSimulationSystemGroup>().ServerTick;

        var fingers = LeanTouch.GetFingers(true, false);

        if (fingers.Count == 1 && fingers[0].Down)
        {
            var ray = Camera.main.ScreenPointToRay(Input.mousePosition);

            if (GameReferences.Instance.raycastPlane.Raycast(ray, out var dist))
            {
                startPoint = ray.GetPoint(dist);
                GameReferences.Instance.selection.gameObject.SetActive(true);
                GameReferences.Instance.selection.position = startPoint;
            }
        }

        if (fingers.Count == 1 && fingers[0].Set)
        {
            var ray = Camera.main.ScreenPointToRay(Input.mousePosition);

            if (GameReferences.Instance.raycastPlane.Raycast(ray, out var dist))
            {
                var point = ray.GetPoint(dist);

                var selectionSize = point - startPoint;
                selectionSize.y = 1;
                GameReferences.Instance.selection.localScale = selectionSize;
            }
        }

        if (fingers.Count == 1 && fingers[0].Up)
        {
            GameReferences.Instance.selection.gameObject.SetActive(false);
            var ray = Camera.main.ScreenPointToRay(Input.mousePosition);

            if (GameReferences.Instance.raycastPlane.Raycast(ray, out var dist))
            {
                endPoint = ray.GetPoint(dist);

                if (SelectionIsValid())
                {
                    SetSelection(ref input);
                }
                else
                {
                    if (hasSelection)
                    {
                        SetDestination(ref input);
                        GameReferences.Instance.ConsumeBuildEvent();
                    }
                }
            }
        }

        // add build input
        if (MapInteractions.Instance.GetPendingInput(out var buildInput))
        {
            input.buildX = buildInput.x;
            input.buildZ = buildInput.z;
        }

        var inputBuffer = EntityManager.GetBuffer <PlayerInput>(localInput);

        inputBuffer.AddCommandData(input);
    }
Ejemplo n.º 23
0
    protected override void Update()
    {
        base.Update();
        txtReload.text = currentAmmo + "/" + AmmoPerClip;
        ShowMessage("Reloading", "Is Reloading: " + Convert.ToInt32(isReloading));
        ShowMessage("MiniReloading", "Is Adjusting Gun: " + Convert.ToInt32(isMiniReloading));

        if (Target != null && (Target.GetComponent <Enemy>() && Target.GetComponent <Enemy>().Alive))
        {
            if (Physics.Raycast(ScopeCamera.transform.position, ScopeCamera.transform.forward))
            {
                distanceToTarget = Vector3.Distance(BulletSpawnLocation.position, Target.transform.position);
            }
            else
            {
                distanceToTarget = 0;
            }
            txtDistanceToTarget.text = Mathf.Round(distanceToTarget) + "m";
        }
        else
        {
            txtDistanceToTarget.text = "";
        }


        if (IsUserControllable)
        {
            ZoomPinchControls(false);
            if (!isReloading)
            {
                RotationControls(false, true);
            }
            //Time Freeze output
            ShowMessage("TimeFreeze", "Time Freeze : " + Convert.ToInt32(InTimeFreezeMode));

            if (isReloading)
            {
                ReloadQuicktime();
            }


            List <LeanFinger> fingers = LeanTouch.GetFingers(false);

            if (fingers.Count > 0 && !isMiniReloading && CanAutoFire)
            {
                if (LeanGesture.GetScreenDelta().magnitude > 0 || isZooming)
                {
                    panning = true;
                }

                Ray        ray = fingers[0].GetRay();
                RaycastHit hit = default(RaycastHit);
                if (Physics.Raycast(ray, out hit, LayerMask.NameToLayer(ScopeLayerName)) && !panning)
                {
                    //Check if we should exit scope mode
                    if (hit.transform.gameObject.layer != LayerMask.NameToLayer(TouchableLayerName))
                    {
                        fireTime += Time.deltaTime;
                        if (fireTime >= TimeBetweenShots)
                        {
                            OnFireBegin();
                            fireTime = 0;
                        }
                    }
                }
            }
        }
    }
Ejemplo n.º 24
0
    protected override void RotationControls(bool ignoreGUI = true, bool linear = false)
    {
        //For smooth rotation
        Vector3 prevEuler = new Vector3(xRot, yRot, 0);

        List <LeanFinger> fingers = LeanTouch.GetFingers(ignoreGUI);

        Vector3[] corners = new Vector3[4];
        ScopeUICenter.transform.GetChild(0).GetComponent <RectTransform>().GetWorldCorners(corners);
        Vector3 pivot = corners[0];

        for (int i = 0; i < fingers.Count; i++)
        {
            if (fingers[i].LastScreenPosition.x > corners[0].x)
            {
                fingers.RemoveAt(i);
                i--;
            }
        }



        //Optional linear mode
        float sens = RotationSensitivity;

        if (linear && ViewingScope)
        {
            if (Zoom != 0)
            {
                sens = RotationSensitivity * InvZoom(Zoom, MinimumRotationModifier);
            }
            else
            {
                sens = RotationSensitivity;
            }
        }


        //Change in finger position (sliding)
        Vector2 delta = LeanGesture.GetScreenDelta(fingers) * sens;

        //For the x rotation, we don't use the Camera's euler angles directly.
        //We initialize xRot to zero before this method (since we're using localEulerAngles), then we constanly subtract delta.y
        //Then we clamp that independent value, and apply to the localEulerAngles.
        //Inspired from joel_b on http://answers.unity3d.com/questions/18680/limiting-rotation-of-an-object.html


        xRot -= delta.y;
        yRot += delta.x;


        if (RestrictXRotation)
        {
            xRot = WrapAngle(Mathf.Clamp(xRot, MinXRotation, MaxXRotation));
        }
        if (RestrictYRotation)
        {
            yRot = WrapAngle(Mathf.Clamp(yRot, MinYRotation, MaxYRotation));
        }


        //
        //Root.transform.rotation = Quaternion.Euler();

        if (ExtraSmooth)
        {
            Quaternion look = Quaternion.Euler(new Vector3(xRot, yRot, 0));
            if (RotationSmooth != -1)
            {
                Root.rotation = Quaternion.Slerp(Root.rotation, look, RotationSmooth);
            }
            else
            {
                Root.rotation = Quaternion.Slerp(Root.rotation, look, RotationSensitivity);
            }
        }
        else
        {
            if (RotationSmooth != -1)
            {
                Root.transform.eulerAngles = Vector3.Lerp(prevEuler, new Vector3(xRot, yRot, 0), RotationSmooth);
            }
            else
            {
                Root.transform.eulerAngles = Vector3.Lerp(prevEuler, new Vector3(xRot, yRot, 0), RotationSensitivity);
            }
        }



        ShowMessage("CameraAngle", "Camera Angle : " + CameraRotation.ToString());
    }
Ejemplo n.º 25
0
        protected virtual void LateUpdate()
        {
            if (!_isActive)
            {
                return;
            }
            var fingers     = LeanTouch.GetFingers(IgnoreGuiFingers, RequiredFingerCount);
            var screenDelta = LeanGesture.GetScreenDelta(fingers);

            screenDelta.x /= Screen.width;
            screenDelta.y /= Screen.height;
            var oldPosition = _transform.localPosition;

            _transform.Translate(new Vector3(screenDelta.x, 0f, screenDelta.y) * MoveSensitivity, Space.Self);
            _moveRemainingDelta += _transform.localPosition - oldPosition;
            if (_camera.orthographic)
            {
                _moveRemainingDelta.y = 0f;
            }
            var factor   = LeanTouch.GetDampenFactor(MoveDampening, Time.deltaTime);
            var newDelta = Vector3.Lerp(_moveRemainingDelta, Vector3.zero, factor);

            _transform.localPosition = oldPosition + _moveRemainingDelta - newDelta;
            _isMoving           = screenDelta.sqrMagnitude > 0.1f;
            _moveRemainingDelta = newDelta;
            if (_transform.position.x < _limitsOffset.x + _limitsX.x || _transform.position.x > _limitsOffset.x + _limitsX.y)
            {
                var limitedPos = _transform.localPosition;
                limitedPos.x             = oldPosition.x;
                _transform.localPosition = limitedPos;
                _moveRemainingDelta.x    = 0f;
            }
            if (_transform.position.z < _limitsOffset.y + _limitsZ.x || _transform.position.z > _limitsOffset.y + _limitsZ.y)
            {
                var limitedPos = _transform.localPosition;
                limitedPos.z             = oldPosition.z;
                _transform.localPosition = limitedPos;
                _moveRemainingDelta.z    = 0f;
            }
            var pinchRatio = LeanGesture.GetPinchRatio(fingers, ZoomWheelSensitivity);

            if (_camera.orthographic)
            {
                _zoom *= pinchRatio;
                _zoom  = Mathf.Clamp(_zoom, _orthoLimits.x, _orthoLimits.y);
                _camera.orthographicSize = _zoom;
            }
            else
            {
                _zoom *= pinchRatio;
                _zoom  = Mathf.Clamp(_zoom, _terrainOffsetMin, _terrainOffsetMax);
                var pos    = _transform.position;
                var height = 0f;
                if (_terrain != null)
                {
                    height = _terrain.SampleHeight(pos) + _zoom;
                }
                else
                {
                    height = _offsetFromFloorIfNoTerrain + _zoom;
                }
                pos.y = height;
                _transform.position = pos;
            }
            var twistDegrees = LeanGesture.GetTwistDegrees(fingers);
            var rotation     = _transform.localEulerAngles;

            rotation.y += twistDegrees;
            //_transform.localEulerAngles = rotation;
        }
Ejemplo n.º 26
0
    void LateUpdate()
    {
        //if (IgnoreTouch)
        //{
        //    return;
        //}
        isMoved = false;
        Vector3 beforeMove = transform.position;
        bool    zoomed     = touchZoom();

        if (!zoomed && !freezeMove)
        {
            if (isSnapMove)
            {
                beginMove();
                if (isSmoothMove)
                {
                    transform.position = Vector3.SmoothDamp(transform.position, targetPosition, ref velocity, smoothTime, snapMoveMutiply);
                }
                else
                {
                    transform.position = Vector3.Lerp(transform.position, targetPosition, Time.deltaTime * snapMoveMutiply);
                }
                updateCameraRect();
                if (isMovedToTarget())
                {
                    endMove();
                    isSnapMove = false;
                }
            }
            else if (isSwipeMove)
            {
                beginMove();
                transform.position = Vector3.SmoothDamp(transform.position, targetPosition, ref velocity, smoothTime);
                updateCameraRect();
                if (isMovedToTarget())
                {
                    endMove();
                    isSwipeMove = false;
                }
            }
            else if (isFingerSet)
            {
                // isFingerDown = false;
                var fingers         = LeanTouch.GetFingers(IgnoreStartedOverGui, IgnoreIsOverGui, 1);
                var lastScreenPoint = LeanGesture.GetLastScreenCenter(fingers);
                var screenPoint     = LeanGesture.GetScreenCenter(fingers);
                var worldDelta      = ScreenDepth.ConvertDelta(lastScreenPoint, screenPoint, Camera, gameObject);
                if (worldDelta != Vector3.zero)
                {
                    beginMove();
                    transform.position -= worldDelta;
                    updateCameraRect();
                }
            }
        }

        if (isSnapZoom && !freezeZoom)
        {
            if (isSmoothZoom)
            {
                //snapZoomMutiply *= ((ZoomSteps+1) * (ZoomSteps + 1) / Mathf.Pow(Mathf.Abs(targetSize - currentSize)+1, 1));
                ZoomSteps += Time.deltaTime;
                //currentSize = Mathf.SmoothStep(currentSize, targetSize, Time.deltaTime * snapZoomMutiply);
                currentSize = SineEaseOut(ZoomSteps, ZoomStart, targetSize - ZoomStart, snapZoomMutiply);
            }
            else
            {
                currentSize = Mathf.Lerp(currentSize, targetSize, Time.deltaTime * snapZoomMutiply);
            }
            SetZoom();
            if (Mathf.Abs(currentSize - targetSize) < 0.01f)
            {
                currentSize = targetSize;
                SetZoom();
                zoomed = true;
                endZoom();
                isSnapZoom = false;
            }
        }

        if (isMoved || zoomed)
        {
            actualMoveDelta = transform.position - beforeMove;
            if (scrollZoomEvent != null)
            {
                scrollZoomEvent.OnViewRectChange();
            }
        }
    }
Ejemplo n.º 27
0
        /// <summary>
        /// Update current input.
        /// </summary>
        public void PollInput()
        {
            var touches = LeanTouch.GetFingers(false, false);

            for (int i = 0; i < touches.Count; i++)
            {
                LeanFinger f = touches[i];
                int        index;

                //released
                if (f.Up)
                {
                    index = IdIndex(f.Index);
                    if (index != -1)
                    {
                        TouchPoint tp = touchPoints[index];
                        touchPoints[index] = TouchPoint.Null;
                        if (tp.track != -1)
                        {
                            tracksHeld[tp.track]--;
                        }
                    }

                    continue;
                }

                //no more space
                if (SafeIndex() == MaxTouches)
                {
                    continue;
                }
                index = IdIndex(f.Index);

                //tapped
                //hardware index does not exist == touch was registered just now == tap
                if (index == -1)
                {
                    (float2? exact, Rect2D? ipt, int track) = Projection.PerformInputRaycast(CameraCast.ScreenPointToRay(f.ScreenPosition));
                    touchPoints[safeIndex] = new TouchPoint(exact, ipt, track, PlayManager.Conductor.receptorTime, TouchPoint.Status.Tapped, f.Index);

                    if (track != -1)
                    {
                        tracksHeld[track]++;
                    }

                    continue;
                }

                //has not moved significantly
                if (math.lengthsq(f.ScaledDelta) < TouchEps)
                {
                    TouchPoint tp = touchPoints[index];

                    tp.status = TouchPoint.Status.Sustained;

                    touchPoints[index] = tp;
                }
                //has moved
                else
                {
                    TouchPoint tp     = touchPoints[index];
                    int        oTrack = tp.track;

                    (tp.inputPosition, tp.inputPlane, tp.track) = Projection.PerformInputRaycast(CameraCast.ScreenPointToRay(f.ScreenPosition));
                    tp.status = TouchPoint.Status.Sustained;

                    touchPoints[index] = tp;

                    if (oTrack != tp.track)
                    {
                        if (oTrack != -1)
                        {
                            tracksHeld[oTrack]--;
                        }
                        if (tp.track != -1)
                        {
                            tracksHeld[tp.track]++;
                        }
                    }
                }
            }
        }