Holding the ball

When the player begins to toss the ball, they'll touch and drag it in a flick gesture. We can add that now to the script.

Add the following to the top of the class:

   private Vector3 inputPositionCurrent; 
   private Vector2 inputPositionPivot; 
   private Vector2 inputPositionDifference; 
 
   private RaycastHit raycastHit; 
 

Add the OnTouch function:

    void OnTouch() { 
        inputPositionCurrent.z = ballStartZ; 
        newBallPosition = Camera.main.ScreenToWorldPoint(inputPositionCurrent); 
        transform.localPosition = newBallPosition; 
    } 

Update(), on each frame, handles user input. Note that we use the UNITY_EDITOR directive variable to conditionally include code for input via mouse versus input via mobile screen touch:

    void Update() { 
        bool isInputBegan = false; 
        bool isInputEnded = false; 
#if UNITY_EDITOR 
        isInputBegan = Input.GetMouseButtonDown(0); 
        isInputEnded = Input.GetMouseButtonUp(0); 
        inputPositionCurrent = Input.mousePosition; 
#else 
   isInputBegan = Input.touchCount == 1 && Input.GetTouch(0).phase == TouchPhase.Began; 
   isInputEnded = Input.touchCount == 1 && Input.GetTouch(0).phase == TouchPhase.Ended; 
   isInputLast = Input.touchCount == 1; 
   inputPositionCurrent = Input.GetTouch (0).position; 
#endif 
        if (isHolding) 
            OnTouch(); 
 
        if (isThrown) 
            return; 
 
        if (isInputBegan) { 
            if (Physics.Raycast(Camera.main.ScreenPointToRay(inputPositionCurrent), out raycastHit, 100f)) { 
                if (raycastHit.transform == transform) { 
                    isHolding = true; 
                    transform.SetParent(null); 
                    inputPositionPivot = inputPositionCurrent; 
                } 
            } 
        } 
 
        if (isInputEnded) { 
            if (inputPositionPivot.y < inputPositionCurrent.y) { 
                Throw(inputPositionCurrent); 
            } 
        } 
    } 
 
    void Throw(Vector2 inputPosition) { 
    } 

You can see we've separated the input states between isInputBegan and IsInputEnded. When it's began, we move the ball, mapping from screen coordinates of the input to world coordinates. When input ends, we will call Throw().

Save the script and, when you press Play, you can select and drag the ball across the screen.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset