Touchphase.Ended не запускается - PullRequest
       0

Touchphase.Ended не запускается

0 голосов
/ 12 января 2020

Я пытаюсь придать силу объекту rigidbody прикосновением, оттащить от него и затем отпустить прикосновение. Но Touchphase.End просто не работает. Я не могу найти ответ на эту проблему. Я получаю ввод одним касанием до тех пор, пока касание не отпустится, после отпускания касания рассчитывается расстояние между начальной и конечной позицией, и аналогичная сила применяется к rigidbody, чтобы заставить его двигаться. Объект, к которому прикреплен код, - это тот же объект, который необходимо переместить.

   // Update is called once per frame
    void Update()
    {
        //Update the Text on the screen depending on current TouchPhase, and the current direction vector

        // Track a single touch as a direction control.
        if (Input.GetMouseButton(0))
        {

                Touch touch = Input.GetTouch(0);
                _touchPosWorld =
                    Camera.main.ScreenToWorldPoint(touch.position); //get the position where the screen was touched

                RaycastHit2D hitInformation = Physics2D.Raycast(_touchPosWorld, Vector2.zero);
                FirstTouch = (hitInformation.collider.CompareTag("ball"));


                if (FirstTouch || IsInTouch)
                {
                    // Handle finger movements based on TouchPhase
                    switch (touch.phase)
                    {
                        //When a touch has first been detected, change the message and record the starting position
                        case TouchPhase.Began:
                            // Record initial touch position.

                            IsInTouch = true;
                            _startPos = touch.position;
                            GameManager.GetInstance().ChangeAccordinglyText.text = "clicked Inside";//test text


                            //Movement started
                            break;

                        //Determine if the touch is a moving touch
                        case TouchPhase.Moved:
                            // Determine direction by comparing the current touch position with the initial one
                            _direction = touch.position - _startPos;

                            GameManager.GetInstance().ChangeAccordinglyText.text = "MovingTouch to " + touch.position; //test text 


                            //moving
                            break;

                        case TouchPhase.Ended:
                            // Report that the touch has ended when it ends
                            //end of movement of touch

                            GameManager.GetInstance().EndedText.text = "EndOfTouch";

                            float force = 0;
                            force = _direction.x > _direction.y ? _direction.x : _direction.y;
                            _rigidbody.AddForce(_direction * force);
                            FirstTouch = false;
                            IsInTouch = false;
                            break;

                }
            }
        }
    }

1 Ответ

0 голосов
/ 13 января 2020

Ваш TouchPhase.End никогда не будет достигнут, так как в момент отпускания касания также GetMouseButton(0) будет false и, таким образом, весь блок будет пропущен!


Чтобы избежать ошибок, о которых вы говорите, прежде чем пытаться получить доступ к определенному касанию, сначала проверьте, есть ли какое-либо касание для доступа с помощью Input.touchCount

if(Input.touchCount > 0)
{
    var touch = Input.GetTouch(0);

    // ...
}

В общем для развитие, вы должны скорее проверить, например, Input.touchSupported и реализовать альтернативную систему мыши для моделирования касаний

if(Input.touchSupported)
{
    /* Implement touches */ 
    if(Input.touchCount > 0)
    {
        var touch = Input.GetTouch(0);

        // ...
    }
} 

// Optional
else 
{ 
    /* alternative mouse implementation for development */
    if(Input.GetMouseButtonDown(0))
    {
        // simulates touch begin
    }
    else if(Input.GetMouseButton(0))
    {
        // simulates touch moved
    }

    // I've seen in strange occasions that down and up might get called within one frame
    if(Input.GetMouseButtonUp(0))
    {
        // simulates touch end
    }
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...