Throwing the ball

Now, we'll add the throw when you release the ball. First, let's add a couple of public variables to help tune the throwing behavior:

    public Vector2 sensivity = new Vector2(8f, 100f); 
    public float speed = 5f; 
    public float resetBallAfterSeconds = 3f; 
 
    private Vector3 direction; 

And the Throw() function itself as follows:

    void Throw(Vector2 inputPosition) { 
       _rigidbody.constraints = RigidbodyConstraints.None; 
       _rigidbody.useGravity = true; 
 
        inputPositionDifference.y = (inputPosition.y - inputPositionPivot.y) / Screen.height * sensivity.y; 
 
        inputPositionDifference.x = (inputPosition.x - inputPositionPivot.x) / Screen.width; 
        inputPositionDifference.x = 
            Mathf.Abs(inputPosition.x - inputPositionPivot.x) / Screen.width * sensivity.x * inputPositionDifference.x; 
 
        direction = new Vector3(inputPositionDifference.x, 0f, 1f); 
        direction = Camera.main.transform.TransformDirection(direction); 
 
        _rigidbody.AddForce((direction + Vector3.up) * speed * inputPositionDifference.y); 
 
        isHolding = false; 
        isThrown = true; 
 
        if (_rigidbody) 
            Invoke("ReadyBall", resetBallAfterSeconds); 
    } 

Throw() is called when the player untouches the screen to toss the ball. It enables the Rigidbody. Then, it figures out a force to apply to the ball based on how far the ball was flicked on the screen (inputPositionDifference), direction, and speed.

Press Play, toss the ball, and it goes flying into the scene!

Experiment with the ball sensitivity and speed parameters to get the game to work the way you like it. Our settings are shown in the following screenshot:

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

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