Ready ball

To begin, in your Project Assets/ARPlayBall/Scripts folder create, a new C# script named ThrowControl and open it for editing. First, we'll write the following code that resets the ball to its ready state:

File: ThrowControl.cs
using UnityEngine; using UnityEngine.Events; public class ThrowControl : MonoBehaviour { public float ballStartZ = 0.5f; public UnityEvent OnReset; private Vector3 newBallPosition; private Rigidbody _rigidbody; private bool isHolding; private bool isThrown; private bool isInitialized = false; void Start() { _rigidbody = GetComponent<Rigidbody>(); ReadyBall(); isInitialized = true; } void Update() { } void ReadyBall() { CancelInvoke(); Vector3 screenPosition = new Vector3(0.5f, 0.1f, ballStartZ); transform.position = Camera.main.ViewportToWorldPoint(screenPosition); newBallPosition = transform.position; isThrown = isHolding = false; _rigidbody.useGravity = false; _rigidbody.velocity = Vector3.zero; _rigidbody.angularVelocity = Vector3.zero; transform.rotation = Quaternion.Euler(0f, 200f, 0f); transform.SetParent(Camera.main.transform); if (isInitialized) OnReset.Invoke(); }

In Start() we get the ball's Rigidbody component and then call ReadyBall.

In ReadyBall, we position the ball a given distance from the camera, in 3D world coordinates so it appears half visible on the bottom of the screen. This is accomplished using the camera ViewportToWorldPoint function given the desired screen position and parent it to the camera. We also disable the ball's rigid body so the ball won't go anywhere right now.

ReadyBall also invokes an OnReset event, passing along the message to any listeners. Specifically, the BallGame component will want to know that the throw is done and ready to go again, so it can update the current score, for example:

  1. Save the file.
  2. And attach the script as a component of the Ball.

Press Play. You should see the ball at the bottom of the screen. If you want to adjust the apparent starting size of the ball, adjust its Z distance from the camera value. The following is a live capture of my screen with the ball in ready position and the game court instantiated:

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

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