Example #1
0
 public TokenMarker(int id, Vector2 postion, TouchState state, MarkerType type)
 {
     this._id = id;
     this._position = postion;
     this._state = state;
     this._type = type;
 }
 public void Touch(Point position)
 {
     if (!this.firstTouch.HasValue)
     {
         this.firstTouch = DateTime.Now;
         return;
     }
     else if (DateTime.Now.Subtract(this.firstTouch.Value).TotalMilliseconds < 100)
     {
         return;
     }
     this.Position = position;
     if (!this.IsActive)
     {
         this.Activate();
     }
     if (this.TouchState != TouchState.Down)
     {
         this.Dispatcher.Invoke(new Func<bool>(this.ReportDown));
         this.TouchState = TouchState.Down;
     }
     else
     {
         this.Dispatcher.Invoke(new Func<bool>(this.ReportMove));
     }
 }
Example #3
0
		internal Touch (TouchState state, Vector2 point, Vector2 surfacePoint, long index = 0, bool isVirtual = false) {
			this.State = state;
			this.Point = point;
			this.SurfacePoint = surfacePoint;
			this.Index = index;
			this.IsVirtual = isVirtual;
		}
Example #4
0
 /**
  * @brief	タッチ情報オールリセット;
  * @note
  */
 public static void resetAll()
 {
     mHitObject = null;
     mTouchState = TouchState.NON;
     mMousePos[(int)TouchState.SLIDE_START] = mTempMousePos[(int)TouchState.SLIDE_START] = new Vector2(0.0f, 0.0f);
     mMousePos[(int)TouchState.SLIDE_END] = mTempMousePos[(int)TouchState.SLIDE_END] = new Vector2(0.0f, 0.0f);
     mScreenSlide = false;
 }
 public void NoTouch()
 {
     this.firstTouch = null;
     if (TouchState == TouchState.Down)
     {
         this.Dispatcher.Invoke(new Func<bool>(this.ReportUp));
     }
     this.TouchState = TouchState.Up;
 }
Example #6
0
        public TouchInput(int id, Vector2 position, TouchState state)
        {
            this.Id = id;
            this.Position = position;
            this.State = state;

            //ClusterId is initially set to null and updated when first inseted
            //into a new Cluster
            this.ClusterId = null;
        }
Example #7
0
		List<TouchInfo> getList(TouchState key)
		{
			List<TouchInfo> result;
			if (!actionTask.TryGetValue(key, out result))
			{
				result = new List<TouchInfo>();
				actionTask.Add(key, result);
			}
			return result;
		}
Example #8
0
    public bool Init()
    {
        for (int i = 0; i < MaxTouchCount; ++i)
            TouchStates[i] = new TouchState();

        if (!InitFilter())
            return false;

        return true;
    }
Example #9
0
		public void Init(Touch touch)
		{
			this.fingerID = touch.fingerId;
			this.stateTime = touch.deltaTime;
			this.totalTime = touch.deltaTime;
			this.pos = touch.position;
			this.deltaPos = touch.deltaPosition;
			this.totalVec = touch.deltaPosition;
			this.state = TouchStateUtil.PhaseToState(touch.phase);
		}
Example #10
0
        private async Task SetBackgroundColorAsync(TouchEff sender, TouchState state, int duration)
        {
            var regularBackgroundColor = sender.RegularBackgroundColor;
            var pressedBackgroundColor = sender.PressedBackgroundColor;

            if (regularBackgroundColor == Color.Default &&
                pressedBackgroundColor == Color.Default)
            {
                return;
            }

            var color  = regularBackgroundColor;
            var easing = sender.RegularAnimationEasing;

            if (state == TouchState.Pressed)
            {
                color  = pressedBackgroundColor;
                easing = sender.PressedAnimationEasing;
            }

            var control = sender.Control;

            if (duration <= 0)
            {
                control.BackgroundColor = color;
                return;
            }

            var animationCompletionSource = new TaskCompletionSource <bool>();

            new Animation {
                { 0, 1, new Animation(v => control.BackgroundColor = new Color(v, control.BackgroundColor.G, control.BackgroundColor.B, control.BackgroundColor.A), control.BackgroundColor.R, color.R) },
                { 0, 1, new Animation(v => control.BackgroundColor = new Color(control.BackgroundColor.R, v, control.BackgroundColor.B, control.BackgroundColor.A), control.BackgroundColor.G, color.G) },
                { 0, 1, new Animation(v => control.BackgroundColor = new Color(control.BackgroundColor.R, control.BackgroundColor.G, v, control.BackgroundColor.A), control.BackgroundColor.B, color.B) },
                { 0, 1, new Animation(v => control.BackgroundColor = new Color(control.BackgroundColor.R, control.BackgroundColor.G, control.BackgroundColor.B, v), control.BackgroundColor.A, color.A) },
            }.Commit(sender.Control, ChangeBackgroundColorAnimationName, 16, (uint)duration, easing, (d, b) => animationCompletionSource.SetResult(true));
            await animationCompletionSource.Task;
        }
Example #11
0
        private int GetTouchCount(TouchState _state)
        {
            int _count = -1;

#if UNITY_EDITOR
            switch (_state)
            {
            case TouchState.None:
            case TouchState.TouchUp:
                if (Input.GetMouseButtonUp(0) == true || Input.GetMouseButtonUp(1) == true)
                {
                    _count = 0;
                }
                break;

            case TouchState.Touch:
            case TouchState.Touch_Long:
            case TouchState.TouchDrag_1Point:
                if (Input.GetMouseButtonDown(0) == true)
                {
                    _count = 1;
                }
                break;

            case TouchState.TouchDrag_2Point:
                if (Input.GetMouseButtonDown(1) == true)
                {
                    _count = 2;
                }
                break;
            }
#elif UNITY_IOS || UNITY_ANDROID
            _count = Input.touchCount;
#endif
            return(_count);

            //return 1;
        }
Example #12
0
 // Update is called once per frame
 void Update()
 {
     if (Input.touches.Length > 0)
     {
         Touch   touch  = Input.touches[0];
         Vector3 vector = Camera.main.ScreenToWorldPoint(touch.position);
         if (vector.x > 0f)
         {
             Debug.Log("Right touch");
             _TouchState = TouchState.RightTouch;
         }
         if (vector.x < 0f)
         {
             //Do something if it's the left side
             Debug.Log("Left touch");
             _TouchState = TouchState.LeftTouch;
         }
     }
     else
     {
         _TouchState = TouchState.NoTouch;
     }
 }
 void CheckTouch()
 {
     nowTouchState = CheckTouchState();
     if (nowTouchState != prevTouchState)
     {
         if (nowTouchState == GameManager.TouchState.None)
         {
             myHandle.setRotate(Handle.RotateDir.Stop);
             mySubmarine.setMove(Submarine.MoveDir.Stop);
         }
         else if (nowTouchState == GameManager.TouchState.Left)
         {
             myHandle.setRotate(Handle.RotateDir.Left);
             mySubmarine.setMove(Submarine.MoveDir.Left);
         }
         else
         {
             myHandle.setRotate(Handle.RotateDir.Right);
             mySubmarine.setMove(Submarine.MoveDir.Right);
         }
         prevTouchState = nowTouchState;
     }
 }
Example #14
0
        protected void MoveCameraByTouches(float timeStep)
        {
            const float touchSensitivity = 2f;

            var input = Input;

            for (uint i = 0, num = input.NumTouches; i < num; ++i)
            {
                TouchState state = input.GetTouch(i);
                if (state.Delta.X != 0 || state.Delta.Y != 0)
                {
                    var camera = cameraNode.GetComponent <Camera>();
                    if (camera == null)
                    {
                        return;
                    }

                    yaw   += touchSensitivity * camera.Fov / Graphics.Height * state.Delta.X;
                    pitch += touchSensitivity * camera.Fov / Graphics.Height * state.Delta.Y;
                    cameraNode.Rotation = new Quaternion(pitch, yaw, 0);
                }
            }
        }
Example #15
0
        private async Task SetScaleAsync(TouchEff sender, TouchState touchState, HoverState hoverState, int duration, Easing easing)
        {
            var regularScale = sender.RegularScale;
            var pressedScale = sender.PressedScale;
            var hoveredScale = sender.HoveredScale;

            if (Abs(regularScale - 1) <= double.Epsilon &&
                Abs(pressedScale - 1) <= double.Epsilon &&
                Abs(hoveredScale - 1) <= double.Epsilon)
            {
                return;
            }

            var scale = regularScale;

            if (touchState == TouchState.Pressed)
            {
                scale = pressedScale;
            }
            else if (hoverState == HoverState.Hovering)
            {
                scale = hoveredScale;
            }

            var control = sender.Control;
            var tcs     = new TaskCompletionSource <bool>();

            control.Animate($"{nameof(SetScaleAsync)}{control.Id}", v =>
            {
                if (double.IsNaN(v))
                {
                    return;
                }
                control.Scale = v;
            }, control.Scale, scale, 16, (uint)Abs(duration), easing, (v, b) => tcs.SetResult(b));
            await tcs.Task;
        }
Example #16
0
        public override void Initialise()
        {
            // Initialise victory state
            // ================
            // Initialise Sprites

            m_background   = new Sprite(TextureHandler.victoryBackground, new Vector2(Settings.m_screenWidth / 2, Settings.m_screenHeight / 2), 0, Vector2.One);
            m_leaderboard  = new Sprite(TextureHandler.victoryLeaderboard, new Vector2(Settings.m_screenWidth * 0.25f + 20, Settings.m_screenHeight * 0.25f), 0, new Vector2(1.5f, 1.5f));
            m_goldTrophy   = new Sprite(TextureHandler.victoryTrophyFirst, new Vector2(Settings.m_screenWidth * 0.75f - 20, Settings.m_screenHeight * 0.05f + 20), 0, new Vector2(0.5f, 0.5f));
            m_silverTrophy = new Sprite(TextureHandler.victoryTrophySecond, new Vector2(Settings.m_screenWidth * 0.65f - 25, Settings.m_screenHeight * 0.25f - 40), 0, new Vector2(0.5f, 0.5f));
            m_bronzeTrophy = new Sprite(TextureHandler.victoryTrophyThird, new Vector2(Settings.m_screenWidth * 0.85f, Settings.m_screenHeight * 0.35f), 0, new Vector2(0.5f, 0.5f));

            // Set player podium textures to default cows
            m_playerFirst = new Sprite(TextureHandler.cow1, new Vector2(Settings.m_screenWidth * 0.75f - 20, Settings.m_screenHeight * 0.25f - 40), 180, new Vector2(0.75f, 0.75f));

            if (Settings.m_numberOfPlayers > 1)
            {
                m_playerSecond = new Sprite(TextureHandler.cow2, new Vector2(Settings.m_screenWidth * 0.65f - 25, Settings.m_screenHeight * 0.35f), 180, new Vector2(0.75f, 0.75f));
            }

            if (Settings.m_numberOfPlayers > 2)
            {
                m_playerThird = new Sprite(TextureHandler.cow3, new Vector2(Settings.m_screenWidth * 0.85f, Settings.m_screenHeight * 0.5f - 20), 180, new Vector2(0.75f, 0.75f));
            }

            //           // Initialise Buttons
            m_Race_Again_Button = new Button(TextureHandler.menuPlayAgainButton, new Vector2(Settings.m_screenWidth * 0.25f, Settings.m_screenHeight * 0.8f));
            m_Main_Menu_Button  = new Button(TextureHandler.menuMainMenuButton, new Vector2(Settings.m_screenWidth * 0.75f, Settings.m_screenHeight * 0.8f));


            m_touchState = TouchState.IDLE;

            // Set initial next state
            m_nextState = GameState.MAIN_MENU;
            // Change execution state
            m_currentExecutionState = ExecutionState.RUNNING;
        }
Example #17
0
    public static TouchState getTouchState(int mouseButton = 0)
    {
        TouchState ret = TouchState.touchNone;

        if (Input.touchCount > 0)
        {
            Touch theTouch = Input.touches[0];
            if (theTouch.phase == TouchPhase.Began)
            {
                ret = TouchState.touchBegin;
            }
            else if (theTouch.phase == TouchPhase.Ended || theTouch.phase == TouchPhase.Canceled)
            {
                ret = TouchState.touchEnd;
            }
            else
            {
                ret = TouchState.touchMove;
            }
        }
        else
        {
            if (Input.GetMouseButtonDown(mouseButton))
            {
                ret = TouchState.touchBegin;
            }
            else if (Input.GetMouseButtonUp(mouseButton))
            {
                ret = TouchState.touchEnd;
            }
            else if (Input.GetMouseButton(mouseButton))
            {
                ret = TouchState.touchMove;
            }
        }
        return(ret);
    }
Example #18
0
        void OnTouched(TouchMoveEventArgs eventArgs)
        {
            // Handle GridView scrolling
            if (Input.NumTouches == 1)
            {
                DragGrid(new Vector3(0, -eventArgs.DY * cameraMovementSpeed, 0));
                //gridViewNode.Position += new Vector3(0 /*eventArgs.DX * cameraMovementSpeed*/, -eventArgs.DY * cameraMovementSpeed, 0);
                //System.Console.WriteLine("x: " + gridViewNode.Position.X + " y: " + gridViewNode.Position.Y);
            }
            // Handle panning and pinching
            else if (Input.NumTouches >= 2)
            {
                // Get Touchstates
                TouchState fingerOne = Input.GetTouch(0);
                TouchState fingerTwo = Input.GetTouch(1);

                // Pinching
                if (isPinching(ref fingerOne.Delta.X, ref fingerTwo.Delta.X, ref fingerOne.Delta.Y, ref fingerTwo.Delta.Y))
                {
                    // Get delta distance between both touches
                    double oldDistance   = GetDistance2D(fingerOne.LastPosition.X, fingerTwo.LastPosition.X, fingerOne.LastPosition.Y, fingerTwo.LastPosition.Y);
                    double newDistance   = GetDistance2D(fingerOne.Position.X, fingerTwo.Position.X, fingerOne.Position.Y, fingerTwo.Position.Y);
                    double deltaDistance = oldDistance - newDistance;

                    // Precision control
                    if (Math.Abs(deltaDistance) > pinchPrecision)
                    {
                        float scale = (float)(newDistance / oldDistance);
                        pinchZoom = (newDistance > oldDistance) ? scale : -scale;

                        // Update camera offset
                        cameraPositionOffset.Z += pinchZoom * zoomFactor;
                    }
                }
            }
        }
Example #19
0
        private async Task SetTranslationAsync(TouchEff sender, TouchState touchState, HoverState hoverState, int duration, Easing easing)
        {
            var regularTranslationX = sender.RegularTranslationX;
            var pressedTranslationX = sender.PressedTranslationX;
            var hoveredTranslationX = sender.HoveredTranslationX;

            var regularTranslationY = sender.RegularTranslationY;
            var pressedTranslationY = sender.PressedTranslationY;
            var hoveredTranslationY = sender.HoveredTranslationY;

            if (Abs(regularTranslationX) <= double.Epsilon &&
                Abs(pressedTranslationX) <= double.Epsilon &&
                Abs(hoveredTranslationX) <= double.Epsilon &&
                Abs(regularTranslationY) <= double.Epsilon &&
                Abs(pressedTranslationY) <= double.Epsilon &&
                Abs(hoveredTranslationY) <= double.Epsilon)
            {
                return;
            }

            var translationX = regularTranslationX;
            var translationY = regularTranslationY;

            if (touchState == TouchState.Pressed)
            {
                translationX = pressedTranslationX;
                translationY = pressedTranslationY;
            }
            else if (hoverState == HoverState.Hovering)
            {
                translationX = hoveredTranslationX;
                translationY = hoveredTranslationY;
            }

            await sender.Control.TranslateTo(translationX, translationY, (uint)Abs(duration), easing);
        }
Example #20
0
    // HandleInput - This will decide if this was as click or a swipe and
    // send a message to all prescribers
    static void HandleInput(TouchState state, ref Vector2 move)
    {
        if ((move.magnitude < minMovMagnitude) || (touchState == TouchState.Stationary))
        {
            //Debug.Log( "CLICK" );
        }
        else if (touchState == TouchState.Move)
        {
            move.Normalize();

            // Left
            if (Mathf.Abs(move.x) > Mathf.Abs(move.y))
            {
                if (move.x > 0.0f)
                {
                    //Debug.Log( "SWIPE: LEFT" );
                }
                else
                {
                    //Debug.Log( "SWIPE: RIGHT" );
                }
            }
            // Right
            else
            {
                if (move.y > 0.0f)
                {
                    //Debug.Log( "SWIPE: DOWN" );
                }
                else
                {
                    //Debug.Log( "SWIPE: UP" );
                }
            }
        }
    }
        protected override void OnUpdate(float timeStep)
        {
            Input input = Input;

            if (character != null)
            {
                // Clear previous controls
                character.Controls.Set(Character.CTRL_FORWARD | Character.CTRL_BACK | Character.CTRL_LEFT | Character.CTRL_RIGHT | Character.CTRL_JUMP, false);

                // Update controls using touch utility class
                touch?.UpdateTouches(character.Controls);

                // Update controls using keys
                if (UI.FocusElement == null)
                {
                    if (touch == null || !touch.UseGyroscope)
                    {
                        character.Controls.Set(Character.CTRL_FORWARD, input.GetKeyDown(Key.W));
                        character.Controls.Set(Character.CTRL_BACK, input.GetKeyDown(Key.S));
                        character.Controls.Set(Character.CTRL_LEFT, input.GetKeyDown(Key.A));
                        character.Controls.Set(Character.CTRL_RIGHT, input.GetKeyDown(Key.D));
                        character.Controls.Set(Character.CTRL_CROUCH, input.GetKeyDown(Key.Ctrl));
                    }
                    character.Controls.Set(Character.CTRL_JUMP, input.GetKeyDown(Key.Space));
                    //character.Controls.Set(Character.CT, input.GetMouseButtonDown(MouseButton.Left));

                    // Add character yaw & pitch from the mouse motion or touch input
                    if (TouchEnabled)
                    {
                        for (uint i = 0; i < input.NumTouches; ++i)
                        {
                            TouchState state = input.GetTouch(i);
                            if (state.TouchedElement == null)    // Touch on empty space
                            {
                                Camera camera = CameraNode.GetComponent <Camera>();
                                if (camera == null)
                                {
                                    return;
                                }

                                var graphics = Graphics;
                                character.Controls.Yaw   += TouchSensitivity * camera.Fov / graphics.Height * state.Delta.X;
                                character.Controls.Pitch += TouchSensitivity * camera.Fov / graphics.Height * state.Delta.Y;
                            }
                        }
                    }
                    else
                    {
                        character.Controls.Yaw   += (float)input.MouseMove.X * YawSensitivity;
                        character.Controls.Pitch += (float)input.MouseMove.Y * YawSensitivity;
                    }
                    // Limit pitch
                    character.Controls.Pitch = MathHelper.Clamp(character.Controls.Pitch, -80.0f, 80.0f);

                    // Switch between 1st and 3rd person
                    if (input.GetKeyPress(Key.F))
                    {
                        firstPerson = !firstPerson;
                    }

                    // Turn on/off gyroscope on mobile platform
                    if (touch != null && input.GetKeyPress(Key.G))
                    {
                        touch.UseGyroscope = !touch.UseGyroscope;
                    }

                    //if (input.GetKeyPress(Key.F5))
                    //{
                    //    var path = FileSystem.ProgramDir + "Data/Scenes";
                    //    FileSystem.CreateDir(path);
                    //    scene.SaveXml(path+ "/CharacterDemo.xml", "\t");
                    //}
                    //   if (input.GetKeyPress(Key.F7))
                    //{
                    //                   var path = FileSystem.ProgramDir + "Data/Scenes";
                    //                   FileSystem.CreateDir(path);
                    //                   scene.LoadXml(path + "/CharacterDemo.xml");
                    //	Node characterNode = scene.GetChild("Jack", true);
                    //	if (characterNode != null)
                    //	{
                    //		character = characterNode.GetComponent<Character>();
                    //	}
                    //	physicsWorld = scene.CreateComponent<PhysicsWorld>();
                    //	physicsWorld.SubscribeToPhysicsPreStep(HandlePhysicsPreStep);
                    //}
                }

                // Set rotation already here so that it's updated every rendering frame instead of every physics frame
                if (character != null)
                {
                    character.Node.Rotation = Quaternion.FromAxisAngle(Vector3.UnitY, character.Controls.Yaw);
                }
            }
        }
Example #22
0
 private void UpdateDragState()
 {
     Vector2 tapDown;
     if( TapDown( out tapDown ) == false ) {
         touchState = TouchState.TapUp;
         SendTapUpMessage( MakeHitInputEvent() );
         lastTouch = currTouch;
     } else if( (tapDown - currTouch.pos).magnitude > deadZone ) {
         currTouch.pos = tapDown;
         SendDragMessage( MakeInputEvent() );  // No raycast for drag
         lastTouch = currTouch;
     }
 }
Example #23
0
 /// <summary>
 /// <para>0x6A touch zapnuto \r\n
 /// 0x4A touch vypnuto</para>
 /// </summary>
 /// <param name="state"></param>
 public bool TouchSettings(TouchState state)
 {
     response = false;
     byte[] txBuff = new byte[] { 0xAA, 0xE0, 0x55, 0xAA, 0x5A, 0xA5, 0x00, 0x07, (byte)state, 0xCC, 0x33, 0xC3, 0x3C };
     comLcdPri.Write(txBuff, 0, txBuff.Length);
     Thread.Sleep(20);
     return response;
 }
Example #24
0
    // only call by other script
    public void GetInputState()
    {
        Vector3 targetPos ;
        switch(mTouchState)
        {
        case TouchState.AFingerOneTap:
            targetPos = RayColliderByTapPos(InputStateClass.touchPointPos);

            if(targetPos != Vector3.zero)
            {
                // turn to the direction first
                SetPlayerToRun(targetPos-this.transform.position);

                // check the attack area
                colliderBaseScript.RayToAttackArea();

        //				Debug.Log(PlayerDataClass.playerAniCmdNext);

                // if there is no enemy in the area, then player start to run
                if(colliderBaseScript.mTarget == null)
                {
                    if(moveBaseScript.curMovementState == PlayerMoveBase.PlayerMovementState.Run
                        ||moveBaseScript.curMovementState == PlayerMoveBase.PlayerMovementState.Walk)
                    {
                        float dis = Vector3.Distance(targetPos,transform.position);
                        if(dis < 4)
                        {
                            ChangeAnimationByActionCmd(PlayerDataClass.PlayerActionCommand.Player_Idel,true);
                        }
                    }
                    else
                    {
                        ChangeAnimationByActionCmd(PlayerDataClass.PlayerActionCommand.Player_Run,true);
                    }
                    colliderBaseScript.mTarget = null;
                    PlayerDataClass.AttackStart = false;
                }
                mTouchState = TouchState.None;
            }
            break;

        case TouchState.AFingerDoubleTap:
            targetPos = RayColliderByTapPos(InputStateClass.touchPointPos);
            SetPlayerToRun(targetPos-this.transform.position);
            ChangeAnimationByActionCmd(PlayerDataClass.PlayerActionCommand.Player_Jump,true);
            mTouchState = TouchState.None;
            break;

        case TouchState.AFingerSlash:
            targetPos = RayColliderByTapPos(InputStateClass.touchPointPos);
            SetPlayerToRun(targetPos-this.transform.position);
            ChangeAnimationByActionCmd(PlayerDataClass.PlayerActionCommand.Player_Rush,true);
            colliderBaseScript.turnOnCatchRay = true;
            colliderBaseScript.mCatchTarget = null;
            mTouchState = TouchState.None;
            break;

        case TouchState.TwoFingersDoubleTap:
            mTouchState = TouchState.None;
            break;

        case TouchState.TwoFingersSlash:
            mTouchState = TouchState.None;
            break;

        case TouchState.TwoFingersTap:
            mTouchState = TouchState.None;
            break;

        default:
            break;
        }
    }
Example #25
0
        internal void HandleTouch(TouchEff sender, TouchStatus status)
        {
            if (sender.IsDisabled)
            {
                return;
            }

            var canExecuteAction = sender.CanExecute;

            if (status != TouchStatus.Started || canExecuteAction)
            {
                if (!canExecuteAction)
                {
                    status = TouchStatus.Canceled;
                }

                var state = status == TouchStatus.Started
                  ? TouchState.Pressed
                  : TouchState.Regular;

                if (status == TouchStatus.Started)
                {
                    _animationProgress = 0;
                    _animationState    = state;
                }

                var isToggled = sender.IsToggled;
                if (isToggled.HasValue)
                {
                    if (status != TouchStatus.Started)
                    {
                        _durationMultiplier = (_animationState == TouchState.Pressed && !isToggled.Value) ||
                                              (_animationState == TouchState.Regular && isToggled.Value)
                            ? 1 - _animationProgress
                            : _animationProgress;

                        sender.Status = status;
                        sender.RaiseStatusChanged();
                        if (status == TouchStatus.Canceled)
                        {
                            sender.ForceUpdateState(false);
                            return;
                        }
                        OnTapped(sender);
                        sender.IsToggled = !isToggled;
                        return;
                    }
                    state = isToggled.Value
                        ? TouchState.Regular
                        : TouchState.Pressed;

                    if (status == TouchStatus.Canceled)
                    {
                        state = state == TouchState.Pressed
                            ? TouchState.Regular
                            : TouchState.Pressed;
                    }
                }

                if (sender.State != state || status != TouchStatus.Canceled)
                {
                    sender.State = state;
                    sender.RaiseStateChanged();
                }
                sender.Status = status;
                sender.RaiseStatusChanged();
            }

            if (status == TouchStatus.Completed)
            {
                OnTapped(sender);
            }
        }
        /// <summary>Updates the state of the input device</summary>
        /// <remarks>
        ///   <para>
        ///     If this method is called with no snapshots in the queue, it will take
        ///     an immediate snapshot and make it the current state. This way, you
        ///     can use the input devices without caring for the snapshot system if
        ///     you wish.
        ///   </para>
        ///   <para>
        ///     If this method is called while one or more snapshots are waiting in
        ///     the queue, this method takes the next snapshot from the queue and makes
        ///     it the current state.
        ///   </para>
        /// </remarks>
        public override void Update()
        {
            TouchState previous = this.current;

              if (this.states.Count == 0) {
            this.current = buildState();
              } else {
            this.current = this.states.Dequeue();
              }

              GenerateEvents(ref previous, ref this.current);
        }
Example #27
0
 internal void SetState(TouchState newState)
 {
     this._state = newState;
 }
Example #28
0
 /**
  * @brief	タッチイベント(離したとき);
  * @note
  */
 public void OnMouseUp()
 {
     // タッチを離した時;
     //	Debug.Log ("MouseUp X:"+Input.mousePosition.x+" Y:"+Input.mousePosition.y);
     mTempMousePos[(int)TouchState.SLIDE_END] = new Vector2 (Input.mousePosition.x, Input.mousePosition.y);
     mTouchState = TouchState.SLIDE_END;
 }
 /// <summary>Checks two touch states for changes an generates events</summary>
 /// <param name="previous">Previous touch state that will be compared</param>
 /// <param name="touchState">New touch state events will be generated for</param>
 protected void GenerateEvents(ref TouchState previous, ref TouchState touchState)
 {
     for (int index = 0; index < touchState.Touches.Count; ++index) {
     switch (touchState.Touches[index].State) {
       case TouchLocationState.Moved: {
     Moved(touchState.Touches[index].Id, touchState.Touches[index].Position);
     break;
       }
       case TouchLocationState.Pressed: {
     Pressed(touchState.Touches[index].Id, touchState.Touches[index].Position);
     break;
       }
       case TouchLocationState.Released: {
     Released(touchState.Touches[index].Id, touchState.Touches[index].Position);
     break;
       }
     }
       }
 }
Example #30
0
 /// <inheritdoc />
 public bool CancelTouch(TouchPoint touch, bool @return)
 {
     int fingerId = -1;
     foreach (var touchState in systemToInternalId)
     {
         if (touchState.Value.Id == touch.Id && touchState.Value.Phase != TouchPhase.Canceled)
         {
             fingerId = touchState.Key;
             break;
         }
     }
     if (fingerId > -1)
     {
         if (@return)
         {
             cancelTouch(touch.Id);
             systemToInternalId[fingerId] = new TouchState(beginTouch(touch.Position, touch.Tags, false).Id);
         }
         else
         {
             systemToInternalId[fingerId] = new TouchState(touch.Id, TouchPhase.Canceled);
             internalCancelTouch(touch.Id);
         }
         return true;
     }
     return false;
 }
Example #31
0
 /**
  * @brief	タッチイベント(押したとき);
  * @note
  */
 public void OnMouseDown()
 {
     // タッチをした時;
     //	Debug.Log ("MouseDown X:"+Input.mousePosition.x+" Y:"+Input.mousePosition.y);
     mTempMousePos[(int)TouchState.SLIDE_START] = new Vector2 (Input.mousePosition.x, Input.mousePosition.y);
     mTouchState = TouchState.SLIDE_START;
 }
Example #32
0
 /**
  * @brief	初期化;
  * @note
  */
 void Start()
 {
     mMousePos = new Vector2[(int)TouchState.EVENT_CNT];
     mTempMousePos = new Vector2[(int)TouchState.EVENT_CNT];
     mTouchState = TouchState.NON;
     mScreenSlide = false;
 }
Example #33
0
 /**
  * @brief	タッチステータスクリア;
  * @note
  */
 private void resetTouchState()
 {
     mTouchState = TouchState.NON;
 }
Example #34
0
 internal void Update(TouchInput t)
 {
     this._id = t.Id;
     this._position = t.Position;
     this._state = t.State;
 }
Example #35
0
//---------------------------------------------------------------------------------------------------------------------

        public void ProcessInput(byte[] bytes)
        {
            switch ((EventType)bytes[0])
            {
            case EventType.Keyboard:
                var type      = (KeyboardEventType)bytes[1];
                var repeat    = bytes[2] == 1;
                var key       = bytes[3];
                var character = (char)bytes[4];
                ProcessKeyEvent(type, repeat, key, character);
                break;

            case EventType.Mouse:
                var deltaX = BitConverter.ToInt16(bytes, 1);
                var deltaY = BitConverter.ToInt16(bytes, 3);
                var button = bytes[5];
                ProcessMouseMoveEvent(deltaX, deltaY, button);
                break;

            case EventType.MouseWheel:
                var scrollX = BitConverter.ToSingle(bytes, 1);
                var scrollY = BitConverter.ToSingle(bytes, 5);
                ProcessMouseWheelEvent(scrollX, scrollY);
                break;

            case EventType.Touch:
            {
                var length  = bytes[1];
                var index   = 2;
                var touches = new TouchState[length];
                for (int i = 0; i < length; i++)
                {
                    const int INPUTSYSTEM_ZERO_ID_GUARD = 128;         //ID 0 is reserved by inputsystem
                    int       identifier = BitConverter.ToInt32(bytes, index) + INPUTSYSTEM_ZERO_ID_GUARD;
                    index += 4;
                    var phase = (UnityEngine.InputSystem.TouchPhase)bytes[index];
                    index += 1;
                    var pageX = BitConverter.ToInt16(bytes, index);
                    index += 2;
                    var pageY = BitConverter.ToInt16(bytes, index);
                    index += 2;
                    var force = BitConverter.ToSingle(bytes, index);
                    index     += 4;
                    touches[i] = new TouchState
                    {
                        touchId  = identifier,
                        phase    = phase,
                        position = new UnityEngine.Vector2Int(pageX, pageY),
                        pressure = force
                    };
                }
                ProcessTouchMoveEvent(touches);
                if (Touch.activeTouches.Count > length)
                {
                    ChangeEndStateUnusedTouches(touches);
                }
            }

            break;

            case EventType.ButtonClick:
                var elementId = BitConverter.ToInt16(bytes, 1);
                ProcessButtonClickEvent(elementId);
                break;

            case EventType.Gamepad:
            {
                GamepadEventType gamepadEventType = (GamepadEventType)bytes[1];

                switch (gamepadEventType)
                {
                case GamepadEventType.ButtonDown:
                case GamepadEventType.ButtonUp:
                case GamepadEventType.ButtonPressed:
                {
                    var buttonIndex = bytes[2];
                    var value       = BitConverter.ToDouble(bytes, 3);
                    ProcessGamepadButtonEvent(gamepadEventType, (GamepadKeyCode)buttonIndex, value);
                }
                break;

                case GamepadEventType.Axis:
                {
                    var buttonIndex = bytes[2];
                    var x           = BitConverter.ToDouble(bytes, 3);
                    var y           = BitConverter.ToDouble(bytes, 11);
                    ProcessGamepadAxisEvent(x, y, (GamepadKeyCode)buttonIndex);
                }
                break;
                }
                InputSystem.QueueStateEvent(RemoteGamepad, m_gamepadState);
            }
            break;
            }
        }
 private static void AddTouchToList(Touch t, TouchState state)
 {
     _touches[t.fingerId] = new TouchInput(t.fingerId, t.position, state);
 }
        Task GetAnimationTask(TouchEffect sender, TouchState touchState, HoverState hoverState, double?durationMultiplier = null)
        {
            if (sender.Element == null)
            {
                return(Task.FromResult(false));
            }

            var token    = animationTokenSource.Token;
            var duration = sender.AnimationDuration;
            var easing   = sender.AnimationEasing;

            if (touchState == TouchState.Pressed)
            {
                if (sender.Element.IsSet(TouchEffect.PressedAnimationDurationProperty))
                {
                    duration = sender.PressedAnimationDuration;
                }

                if (sender.Element.IsSet(TouchEffect.PressedAnimationEasingProperty))
                {
                    easing = sender.PressedAnimationEasing;
                }
            }
            else if (hoverState == HoverState.Hovered)
            {
                if (sender.Element.IsSet(TouchEffect.HoveredAnimationDurationProperty))
                {
                    duration = sender.HoveredAnimationDuration;
                }

                if (sender.Element.IsSet(TouchEffect.HoveredAnimationEasingProperty))
                {
                    easing = sender.HoveredAnimationEasing;
                }
            }
            else
            {
                if (sender.Element.IsSet(TouchEffect.NormalAnimationDurationProperty))
                {
                    duration = sender.NormalAnimationDuration;
                }

                if (sender.Element.IsSet(TouchEffect.NormalAnimationEasingProperty))
                {
                    easing = sender.NormalAnimationEasing;
                }
            }

            if (durationMultiplier.HasValue)
            {
                duration = (int)durationMultiplier.Value * duration;
            }

            duration = Max(duration, 0);

            return(Task.WhenAll(
                       animationTaskFactory?.Invoke(sender, touchState, hoverState, duration, easing, token) ?? Task.FromResult(true),
                       SetBackgroundImageAsync(sender, touchState, hoverState, duration, token),
                       SetBackgroundColor(sender, touchState, hoverState, duration, easing),
                       SetOpacity(sender, touchState, hoverState, duration, easing),
                       SetScale(sender, touchState, hoverState, duration, easing),
                       SetTranslation(sender, touchState, hoverState, duration, easing),
                       SetRotation(sender, touchState, hoverState, duration, easing),
                       SetRotationX(sender, touchState, hoverState, duration, easing),
                       SetRotationY(sender, touchState, hoverState, duration, easing),
                       Task.Run(async() =>
            {
                animationProgress = 0;
                animationState = touchState;

                for (var progress = animationProgressDelay; progress < duration; progress += animationProgressDelay)
                {
                    await Task.Delay(animationProgressDelay).ConfigureAwait(false);
                    if (token.IsCancellationRequested)
                    {
                        return;
                    }

                    animationProgress = (double)progress / duration;
                }
                animationProgress = 1;
            })));
        }
Example #38
0
        private Nullable<TouchLocation> GetTouchSourceNextLocation(Nullable<TouchLocation> currentsource, TouchState touch)
        {
            if (!currentsource.HasValue)
                return null;

            foreach (TouchLocation nextsource in touch.TouchLocations)
            {
                if (currentsource.Value.Id == nextsource.Id)
                    return nextsource;
            }

            return null;
        }
Example #39
0
 internal TouchEff(Func <TouchEff, TouchState, HoverState, int, CancellationToken, Task> animationTaskGetter) : this()
     => _visualManager.SetCustomAnimationTask(animationTaskGetter);
Example #40
0
        private unsafe void UpdateTouch(int touchIndex, int pointerIndex, TouchPhase phase, InputEventPtr eventPtr = default)
        {
            var position = m_CurrentPositions[pointerIndex];
            var touch    = new TouchState
            {
                phase    = phase,
                position = position
            };
            var time = eventPtr.valid ? eventPtr.time : InputState.currentTime;

            var oldTouchState = (TouchState *)((byte *)simulatedTouchscreen.currentStatePtr +
                                               simulatedTouchscreen.touches[touchIndex].stateBlock.byteOffset);

            if (phase == TouchPhase.Began)
            {
                touch.isPrimaryTouch = m_PrimaryTouchIndex < 0;
                touch.startTime      = time;
                touch.startPosition  = position;
                touch.touchId        = ++m_LastTouchId;
                touch.tapCount       = oldTouchState->tapCount; // Get reset automatically by Touchscreen.

                if (touch.isPrimaryTouch)
                {
                    m_PrimaryTouchIndex = touchIndex;
                }
            }
            else
            {
                touch.touchId        = oldTouchState->touchId;
                touch.isPrimaryTouch = m_PrimaryTouchIndex == touchIndex;
                touch.delta          = position - oldTouchState->position;
                touch.startPosition  = oldTouchState->startPosition;
                touch.startTime      = oldTouchState->startTime;
                touch.tapCount       = oldTouchState->tapCount;

                if (phase == TouchPhase.Ended)
                {
                    touch.isTap = time - oldTouchState->startTime <= Touchscreen.s_TapTime &&
                                  (position - oldTouchState->startPosition).sqrMagnitude <= Touchscreen.s_TapRadiusSquared;
                    if (touch.isTap)
                    {
                        ++touch.tapCount;
                    }
                }
            }

            if (touch.isPrimaryTouch)
            {
                InputState.Change(simulatedTouchscreen.primaryTouch, touch, eventPtr: eventPtr);
            }
            InputState.Change(simulatedTouchscreen.touches[touchIndex], touch, eventPtr: eventPtr);

            if (phase.IsEndedOrCanceled())
            {
                m_Touches[touchIndex] = null;
                if (m_PrimaryTouchIndex == touchIndex)
                {
                    m_PrimaryTouchIndex = -1;
                }
            }
        }
Example #41
0
 internal TouchEff(Func <TouchEff, TouchState, HoverState, int, Easing, CancellationToken, Task> animationTaskGetter) : this()
Example #42
0
	/// <summary>
	/// Determines if input was a click or swipe and sends message to all prescribers.
	/// </summary>
	static void HandleInput(TouchState state, ref Vector2 move)
	{
		if ((move.magnitude < minMovMagnitude) || (touchState == TouchState.Stationary))
		{
			//Debug.Log( "CLICK" );
		}
		else if (touchState == TouchState.Move)
		{
			move.Normalize();
			
			// Left
			if(Mathf.Abs(move.x) > Mathf.Abs (move.y))
			{
				if(move.x > 0.0f)
				{
					//Debug.Log( "SWIPE: LEFT" );
				}
				else
				{
					//Debug.Log( "SWIPE: RIGHT" );
				}
			}
			// Right
			else
			{
				if(move.y > 0.0f)
				{
					//Debug.Log( "SWIPE: DOWN" );
				}
				else
				{
					//Debug.Log( "SWIPE: UP" );
				}
			}
		}
	}
 /// <summary>Builds a touch state from the current touches</summary>
 /// <returns>The currently mocked touches in a touch state</returns>
 private TouchState buildState()
 {
     var state = new TouchState(this.isAttached, this.touchCollection);
       TouchCollectionHelper.Clear(ref this.touchCollection);
       return state;
 }
Example #44
0
	static public void Update()
	{
/*
		// TOUCHPAD INPUT
		if (Input.touchCount > 0)
		{
			switch(Input.GetTouch(0).phase)
			{
				case(TouchPhase.Began):
					touchState = TouchState.Down;
					// Get absolute location of touch
					moveAmount = Input.GetTouch(0).position;
					break;
				
				case(TouchPhase.Moved):
					touchState = TouchState.Move;
					break;
				
				case(TouchPhase.Stationary):
					touchState = TouchState.Stationary;
					break;
				
				case(TouchPhase.Ended):
					moveAmount -= Input.GetTouch(0).position;
					HandleInput(touchState, ref moveAmount);
					touchState = TouchState.Init;
					break;
				
				case(TouchPhase.Canceled):
					Debug.Log( "CANCELLED\n" );
					touchState = TouchState.Init;
					break;				
			}
		}	
*/
		// MOUSE INPUT
		if (Input.GetMouseButtonDown(0))
		{
			moveAmountMouse = Input.mousePosition;
			touchState = TouchState.Down;
		}
		else if (Input.GetMouseButtonUp(0))
		{
			moveAmountMouse -= Input.mousePosition;
			HandleInputMouse(ref moveAmountMouse);
			touchState = TouchState.Init;
		}
	}
Example #45
0
    private void UpdateDownState()
    {
        Vector2 tapDown;
        bool isDown = TapDown( out tapDown );
        currTouch.time = Time.time;
        if( isDown ) {
            if ( ( tapDown - currTouch.pos ).magnitude > deadZone ) {
                touchState = TouchState.Dragging;
                lastTouch = currTouch;
            }
        } else {
            // tap up
            if( lastTouch.time != 0 && currTouch.time - lastTouch.time < doubleTapTimeDelta ) {
                SendDoubleTapMessage( MakeHitInputEvent() );
            } else {
                SendSingleTapMessage( MakeHitInputEvent() );
            }
            SendTapUpMessage( MakeHitInputEvent() );
            lastTouch = currTouch;

            touchState = TouchState.TapUp;
            currTouch.pos = Vector3.zero;
            SendTapMessage( MakeInputEvent() );
        }
    }
Example #46
0
        protected override void OnUpdate(float timeStep)
        {
            base.OnUpdate(timeStep);

            var input = Application.Input;

            if ((input.GetMouseButtonDown(MouseButton.Left) || input.NumTouches == 1) && App.TouchedNode == null)
            {
                TouchState state = input.GetTouch(0);
                if (state.Pressure != 1.0)
                {
                    return;
                }

                //App.RootNode.Rotate(new Quaternion(state.Delta.Y, -state.Delta.X, 0), TransformSpace.World);
            }
            else if (input.NumTouches == 2)
            {
                TouchState state1 = input.GetTouch(0);
                TouchState state2 = input.GetTouch(1);

                var distance1 = Distance(state1.Position, state2.Position);

                if (distance1 < 120f)
                {
                    // doing a pan
                    float factor = 0.005f;
                    App.RootNode.Position += new Vector3(-state1.Delta.X * factor, -state1.Delta.Y * factor, 0);
                }
                else
                {
                    var distance2 = Distance(state1.LastPosition, state2.LastPosition);

                    var pos1 = new Vector3(state1.Position.X, state1.Position.Y, 0);
                    var pos2 = new Vector3(state2.Position.X, state2.Position.Y, 0);

                    var v = (pos1 + pos2) / 2;

                    // doing a zoom
                    Zoom((int)(distance1 - distance2), (int)v.X, (int)v.Y);
                    //App.Camera.Zoom += (distance1 - distance2) * 0.01f;
                }
            }

            if (input.GetKeyDown(Key.W) || input.GetKeyDown(Key.Up))
            {
                Pan(PanDirection.Up);
            }
            if (input.GetKeyDown(Key.S) || input.GetKeyDown(Key.Down))
            {
                Pan(PanDirection.Down);
            }
            if (input.GetKeyDown(Key.A) || input.GetKeyDown(Key.Left))
            {
                Pan(PanDirection.Left);
            }
            if (input.GetKeyDown(Key.D) || input.GetKeyDown(Key.Right))
            {
                Pan(PanDirection.Right);
            }
            if (input.GetKeyDown(Key.KP_Plus))
            {
                Zoom(ZoomDirection.In);
            }
            if (input.GetKeyDown(Key.KP_Minus))
            {
                Zoom(ZoomDirection.Out);
            }
        }
Example #47
0
    private void UpdateUpState()
    {
        // Clear touch of tap is up for too long
        if( currTouch.time != 0 && currTouch.time - lastTouch.time < doubleTapTimeDelta ) {
            EndTouchInput();
        }

        Vector2 tapStart;
        if( TapStart( out tapStart ) ) {
            touchState = TouchState.TapDown;
            currTouch.pos = tapStart;
            currTouch.time = Time.time;

            StartTouchInput( tapStart );
            SendTapDownMessage( MakeHitInputEvent() );
        }
    }
 public AnimationStartedEventArgs(TouchState touchState, HoverState hoverState, int duration)
 {
     State      = touchState;
     HoverState = hoverState;
     Duration   = duration;
 }
Example #49
0
 private void SetState(TouchState state)
 {
     _state = state;
 }
 public TouchArgs(TouchState state, bool inside)
 {
     State  = state;
     Inside = inside;
 }
Example #51
0
 /// <summary>
 /// Sets TouchInput State
 /// </summary>
 /// <param name="state">New TouchInput state</param>
 public void SetState(TouchState state)
 {
     this.State = state;
 }
Example #52
0
    // Jump State, basically the mouse code from Simple Player movement,
    // adapted for touch.
    void JumpState()
    {
        stateText.GetComponent <Text>().text = "Jump";

#if UNITY_EDITOR
        if (Input.GetMouseButtonUp(0))
        {
            Vector2 touch = new Vector2(Input.mousePosition.x, Input.mousePosition.y);
            touchPoints [1] = touch;
            state           = TouchState.None;

            if (Vector2.Distance(touchPoints[0], touchPoints[1]) > jumpActivateDist)
            {
                player.GetComponent <SimplePlayerMovement>().Leap(touchPoints [0], touchPoints [1]);
            }

            hideArc();
        }
        else if (Input.GetMouseButton(0))
        {
            Vector2 touch = new Vector2(Input.mousePosition.x, Input.mousePosition.y);
            touchPoints[1] = touch;
            if (Vector2.Distance(touchPoints[0], touchPoints[1]) > jumpActivateDist)
            {
                player.GetComponentInChildren <LaunchArcRenderer>().MakeArc(touchPoints);
            }
            else
            {
                hideArc();
            }
        }
#endif

#if UNITY_ANDROID
        for (int i = 0; i < Input.touchCount; i++)
        {
            Touch touch = Input.touches [i];

            // If you make a second touch stop the Jump
            if (touch.phase == TouchPhase.Began)
            {
                state = TouchState.None;
                hideArc();

                break;

                // Else if you end the Touch get the endpoint and make the leap
            }
            else if (touch.phase == TouchPhase.Ended)
            {
                touchPoints [1] = touch.position;
                state           = TouchState.None;
                if (Vector2.Distance(touchPoints[0], touchPoints[1]) > jumpActivateDist)
                {
                    player.GetComponent <SimplePlayerMovement>().Leap(touchPoints [0], touchPoints [1]);
                }

                hideArc();
                break;

                // This is in case something goes wrong
            }
            else if (touch.phase == TouchPhase.Canceled)
            {
                state = TouchState.None;
                hideArc();
                break;
            }
            else
            {
                touchPoints[1] = touch.position;

                if (Vector2.Distance(touchPoints[0], touchPoints[1]) > jumpActivateDist)
                {
                    player.GetComponentInChildren <LaunchArcRenderer>().MakeArc(touchPoints);
                }
                else
                {
                    hideArc();
                }
            }
        }

        if (Input.touchCount == 0)
        {
            hitText.GetComponent <Text> ().text   = "No hit";
            stateText.GetComponent <Text> ().text = "None";
            hideArc();
            state = TouchState.None;
        }
#endif
    }
        async Task SetBackgroundImageAsync(TouchEffect sender, TouchState touchState, HoverState hoverState, int duration, CancellationToken token)
        {
            var normalBackgroundImageSource  = sender.NormalBackgroundImageSource;
            var pressedBackgroundImageSource = sender.PressedBackgroundImageSource;
            var hoveredBackgroundImageSource = sender.HoveredBackgroundImageSource;

            if (normalBackgroundImageSource == null &&
                pressedBackgroundImageSource == null &&
                hoveredBackgroundImageSource == null)
            {
                return;
            }

            var aspect = sender.BackgroundImageAspect;
            var source = normalBackgroundImageSource;

            if (touchState == TouchState.Pressed)
            {
                if (sender.Element.IsSet(TouchEffect.PressedBackgroundImageAspectProperty))
                {
                    aspect = sender.PressedBackgroundImageAspect;
                }

                source = pressedBackgroundImageSource;
            }
            else if (hoverState == HoverState.Hovered)
            {
                if (sender.Element.IsSet(TouchEffect.HoveredBackgroundImageAspectProperty))
                {
                    aspect = sender.HoveredBackgroundImageAspect;
                }

                if (sender.Element.IsSet(TouchEffect.HoveredBackgroundImageSourceProperty))
                {
                    source = hoveredBackgroundImageSource;
                }
            }
            else
            {
                if (sender.Element.IsSet(TouchEffect.NormalBackgroundImageAspectProperty))
                {
                    aspect = sender.NormalBackgroundImageAspect;
                }
            }

            try
            {
                if (sender.ShouldSetImageOnAnimationEnd && duration > 0)
                {
                    await Task.Delay(duration, token);
                }
            }
            catch (TaskCanceledException)
            {
                return;
            }

            if (sender.Element is Image image)
            {
                using (image.Batch())
                {
                    image.Aspect = aspect;
                    image.Source = source;
                }
            }
        }
Example #54
0
    // Move state, seems to be working now. Most complex so far. Basically if you
    // start a second touch it will check and see if it the two are close enough to
    // start the camera state, if not it just lets the user interact with the UI
    // controlls. A lot of messing around in the Player's movement script, defenitely
    // should be reworked at some point.
    void MoveState()
    {
        stateText.GetComponent <Text>().text = "Move";

#if UNITY_EDITOR
        if (Input.GetMouseButton(0))
        {
            //Vector2 touch = new Vector2(Input.mousePosition.x, Input.mousePosition.y);
            var s = player.GetComponent <SimplePlayerMovement>();

            //Chase's new lines begin
            anim     = player.GetComponent <Animator>();
            grounded = true;
            anim.SetBool("Grounded", grounded);
            anim.SetFloat("Speed", Mathf.Abs(s.xAxis * s.speed));
            if ((s.xAxis * s.speed) < -0.1f)
            {
                //player.transform.localScale =  new Vector3 (-2, 2, 1);
                player.GetComponent <SpriteRenderer>().flipX = true;
            }

            if ((s.xAxis * s.speed) > 0.1f)
            {
                //player.transform.localScale =  new Vector3 (2, 2, 1);
                player.GetComponent <SpriteRenderer>().flipX = false;
            }
            //Chase's new lines ens
        }
        else if (Input.GetMouseButtonUp(0))
        {
            state          = TouchState.None;
            touchPoints[1] = Input.mousePosition;

            float point_dif = (touchPoints[0].y - touchPoints[1].y); //take the differnce between the start point and our end point

            if (Mathf.Abs(point_dif) >= dragDistance)
            {
                Player the_player = player.GetComponent <Player>();
                //Now it should be a swipe
                if (point_dif < 0)
                {
                    the_player.stair_direction = 'u';
                }
                else if (point_dif > 0)
                {
                    the_player.stair_direction = 'd';
                }
            }
        }
        else
        {
            state = TouchState.None;
        }
#endif


#if UNITY_ANDROID
        for (int i = 0; i < Input.touchCount; i++)
        {
            Touch touch = Input.touches [i];

            // Aforementioned check for camera state
            if (touch.phase == TouchPhase.Began && Input.touchCount == 2)
            {
                float diffx =
                    Math.Abs(Input.touches [0].position.x - Input.touches [1].position.x);
                float diffy =
                    Math.Abs(Input.touches [0].position.y - Input.touches [1].position.y);

                if (diffx < cameraActivateDist && diffy < cameraActivateDist)
                {
                    state = TouchState.Camera;
                    player.GetComponent <SimplePlayerMovement> ().xAxis = 0f;
                    touchPoints [0] = Input.touches [0].position;
                    touchPoints [1] = Input.touches [1].position;
                    break;
                }
                else
                {
                    player.GetComponent <SimplePlayerMovement> ().xAxis = 0f;
                }

                // Check if you are ending the last remaining touch.
            }
            else if (touch.phase == TouchPhase.Ended && Input.touchCount == 1)
            {
                state          = TouchState.None;
                touchPoints[1] = touch.position;

                float point_dif = (touchPoints[0].y - touchPoints[1].y); //take the differnce between the start point and our end point

                if (Mathf.Abs(point_dif) >= dragDistance)
                {
                    Player the_player = player.GetComponent <Player>();
                    //Now it should be a swipe
                    if (point_dif < 0)
                    {
                        the_player.stair_direction = 'u';
                    }
                    else if (point_dif > 0)
                    {
                        the_player.stair_direction = 'd';
                    }

                    //The player will reset the stair_direction itself
                }

                break;

                // This bit moves the player on the horizontal axis while you are touching
                // the ui buttons that set the axis value.
            }
            else if ((touch.phase == TouchPhase.Moved ||
                      touch.phase == TouchPhase.Stationary) && Input.touchCount == 1)
            {
                var s = player.GetComponent <SimplePlayerMovement>();

                player.GetComponent <Player>().stair_direction = 'n'; //Make sure the player doesn't think it needs to go in any sort of direction while moving

                //Chase's new lines begin
                anim     = player.GetComponent <Animator>();
                grounded = true;
                anim.SetBool("Grounded", grounded);
                anim.SetFloat("Speed", Mathf.Abs(s.xAxis * s.speed));
                if ((s.xAxis * s.speed) < -0.1f)
                {
                    //player.transform.localScale =  new Vector3 (-2, 2, 1);
                    player.GetComponent <SpriteRenderer>().flipX = true;
                }

                if ((s.xAxis * s.speed) > 0.1f)
                {
                    //player.transform.localScale =  new Vector3 (2, 2, 1);
                    player.GetComponent <SpriteRenderer>().flipX = false;
                }
                //Chase's new lines end
                //Need to store the point that we touched so I can make a comparison when we let go
            }
        }

        if (Input.touchCount == 0)
        {
            hitText.GetComponent <Text> ().text   = "No hit";
            stateText.GetComponent <Text> ().text = "None";
            player.GetComponent <SimplePlayerMovement> ().xAxis = 0f;
            state = TouchState.None;
        }
#endif
    }
Example #55
0
    // ------------------------------------------------------------------
    // Desc:
    // ------------------------------------------------------------------

    void ProcessTouch()
    {
        for (int i = 0; i < Input.touches.Length; ++i)
        {
            Touch touch = Input.touches[i];
            if (touch.fingerId >= 10)
            {
                continue;
            }

            TouchState touchState  = null;
            exUIElement hotElement = PickElement(touch.position);

            //
            if (touch.phase == TouchPhase.Began)
            {
                if (hotElement != null)
                {
                    exUIEvent e = new exUIEvent();
                    e.category = exUIEvent.Category.Touch;
                    e.type     = exUIEvent.Type.TouchDown;
                    e.position = touch.position;
                    e.delta    = touch.deltaPosition;
                    e.touchID  = touch.fingerId;

                    EventInfo info = new EventInfo();
                    info.primaryElement = hotElement;
                    info.uiEvent        = e;
                    eventInfoList.Add(info);
                }

                // NOTE: it must be null
                SetTouchFocus(touch.fingerId, null);
                touchStateList[touch.fingerId].hotElement = hotElement;
            }
            else
            {
                // find the touch state
                touchState = touchStateList[touch.fingerId];

                // set the last and current hot element
                exUIElement focusElement   = null;
                exUIElement lastHotElement = null;
                if (touchState != null)
                {
                    lastHotElement        = touchState.hotElement;
                    touchState.hotElement = hotElement;
                    focusElement          = touchState.focusElement;
                }

                if (touch.phase == TouchPhase.Ended)
                {
                    if (touchState != null)
                    {
                        if (focusElement != null)
                        {
                            exUIEvent e = new exUIEvent();
                            e.category = exUIEvent.Category.Touch;
                            e.type     = exUIEvent.Type.TouchUp;
                            e.position = touch.position;
                            e.delta    = touch.deltaPosition;
                            e.touchID  = touch.fingerId;

                            EventInfo info = new EventInfo();
                            info.primaryElement = focusElement;
                            info.uiEvent        = e;
                            eventInfoList.Add(info);
                        }
                    }
                }
                else if (touch.phase == TouchPhase.Canceled)
                {
                    if (touchState != null)
                    {
                        SetTouchFocus(touch.fingerId, null);
                    }
                }
                else if (touch.phase == TouchPhase.Moved)
                {
                    // process hover event
                    if (lastHotElement != hotElement)
                    {
                        // add hover-in event
                        if (hotElement != null)
                        {
                            exUIEvent e = new exUIEvent();
                            e.category = exUIEvent.Category.Touch;
                            e.type     = exUIEvent.Type.TouchEnter;
                            e.position = touch.position;
                            e.delta    = touch.deltaPosition;
                            e.touchID  = touch.fingerId;

                            EventInfo info = new EventInfo();
                            info.primaryElement = hotElement;
                            info.uiEvent        = e;
                            eventInfoList.Add(info);
                        }

                        // add hover-out event
                        if (lastHotElement != null)
                        {
                            exUIEvent e = new exUIEvent();
                            e.category = exUIEvent.Category.Touch;
                            e.type     = exUIEvent.Type.TouchExit;
                            e.position = touch.position;
                            e.delta    = touch.deltaPosition;
                            e.touchID  = touch.fingerId;

                            EventInfo info = new EventInfo();
                            info.primaryElement = lastHotElement;
                            info.uiEvent        = e;
                            eventInfoList.Add(info);
                        }
                    }

                    //
                    if (hotElement != null || focusElement != null)
                    {
                        exUIEvent e = new exUIEvent();
                        e.category = exUIEvent.Category.Touch;
                        e.type     = exUIEvent.Type.TouchMove;
                        e.position = touch.position;
                        e.delta    = touch.deltaPosition;
                        e.touchID  = touch.fingerId;

                        EventInfo info = new EventInfo();
                        info.primaryElement = (focusElement != null) ? focusElement : hotElement;
                        info.uiEvent        = e;
                        eventInfoList.Add(info);
                    }
                }
            }
        }
    }
Example #56
0
    //Chase's new lines end

    // The None State function. Just looks for 'Began' phase touches and sets the
    // next state according to what was touched
    void NoneState()
    {
        stateText.GetComponent <Text>().text = "None";

#if UNITY_EDITOR
        if (Input.GetMouseButtonDown(0))
        {
            Vector2      touch = new Vector2(Input.mousePosition.x, Input.mousePosition.y);
            Vector3      v3    = Camera.main.ScreenToWorldPoint(touch);
            RaycastHit2D hit   = Physics2D.Raycast(new Vector2(v3.x, v3.y), Vector2.zero,
                                                   10f, touchInputMask);

            if (hit && hit.collider.tag == "JumpRegion")
            {
                hitText.GetComponent <Text> ().text = hit.collider.tag;
                state          = TouchState.Jump;
                touchPoints[0] = touch;
            }
            else
            {
                state           = TouchState.Move;
                touchPoints [0] = touch;
                hitText.GetComponent <Text> ().text = "No hit";
            }
        }
#endif

#if UNITY_ANDROID
        // Basically the same for all of these, we need to loop through the touches
        for (int i = 0; i < Input.touchCount; i++)
        {
            Touch touch = Input.touches[i];

            //This is just raycasting
            Vector3      v3  = Camera.main.ScreenToWorldPoint(touch.position);
            RaycastHit2D hit = Physics2D.Raycast(new Vector2(v3.x, v3.y), Vector2.zero,
                                                 10f, touchInputMask);


            // If you start touching the player, go to Jump State while setting init point
            if (hit && touch.phase == TouchPhase.Began &&
                hit.collider.tag == "JumpRegion" && Input.touchCount == 1)
            {
                hitText.GetComponent <Text>().text = hit.collider.tag;
                state          = TouchState.Jump;
                touchPoints[0] = touch.position;
                break;
            }
            // If not hitting the player, go to Move State
            else if (touch.phase == TouchPhase.Began && Input.touchCount == 1)
            {
                state          = TouchState.Move;
                touchPoints[0] = touch.position;
                hitText.GetComponent <Text>().text = "No hit";
                break;
            }
            else
            {
                hitText.GetComponent <Text>().text = "No hit";
            }
        }

        // Just in case, check for no touches
        if (Input.touchCount == 0)
        {
            hitText.GetComponent <Text>().text   = "No hit";
            stateText.GetComponent <Text>().text = "None";
        }
#endif
    }
 public void Update(TouchState touch)
 {
     ScreenPosition = touch.ScreenPosition;
     Pressure       = touch.Pressure;
 }
Example #58
0
        private Nullable<TouchLocation> FindInitialTouchSource(TouchSourceMovementType touchsourcetype, TouchState touch)
        {
            foreach (TouchLocation source in touch.TouchLocations)
            {
                if (source.SourceIsMouse || source.State != TouchLocationState.Pressed)
                    continue;

                if (touchsourcetype == TouchSourceMovementType.Look && source.NormalizedX > 0.5f)
                    continue;

                if (touchsourcetype == TouchSourceMovementType.Move && source.NormalizedX < 0.5f)
                    continue;

                return source;
            }

            return null;
        }
Example #59
0
 public void RemoveAction(TouchState type, Action <IGestureInfo[]> action)
 {
     actions.Remove(type, action);
 }
Example #60
0
 internal FingerTouch(TouchInput t)
 {
     this._id = t.Id;
     this._position = t.Position;
     this._state = t.State;
 }