Example #1
0
    void Update()
    {
        // Only fire if ball is not moving
        // and is allowed to move (not in pause menu)
        if (move && m_Rigidbody.IsSleeping())
        {
            reset = false;

            // First mouse click press
            if (Input.GetButtonDown("Fire1"))
            {
                charge   = 0.0f;
                released = false;

                // Get starting time
                time = Time.time;

                // Store position before firing
                previousPosition = transform.position;

                // Start playing loading sound
                m_PlaySounds.StartLoading();
            }
            // Mouse click still pressed
            else if (Input.GetButton("Fire1") && !released)
            {
                // Get time elapsed between press and release of left mouse click
                charge = (Time.time - time) % m_ChargeTime;

                // Display slider growing in a loop with return to 0
                m_LoadingSlider.value = (charge / m_ChargeTime);
            }
            // Mouse click released
            else if (Input.GetButtonUp("Fire1") && !released)
            {
                released = true;

                // Apply force to move ball
                Vector3 push = m_Camera.transform.forward.normalized;
                push.y = 0.0f;
                m_Rigidbody.AddForce(push * (charge / m_ChargeTime) * m_Force, ForceMode.Impulse);

                // Increment strokes
                strokes++;
                m_Manager.CountStrokes(strokes);

                // Stop playing loading sound
                m_PlaySounds.EndLoading();
            }
        }
        else
        {
            m_LoadingSlider.value = 0.0f;

            // Reset ball position and speed if out of bounds and not currently being reset
            if (!reset)
            {
                // Check if ground collider contains ball
                if (!m_Collider[0].bounds.Contains(transform.position))
                {
                    Ray        ray = new Ray(transform.position, Vector3.down);
                    RaycastHit hit;
                    reset = true;

                    foreach (Collider collider in m_Collider)
                    {
                        // For all colliders (ground + top + sides),
                        // cast ray right below the ball to check if the ball isnt simply in the air due to a bump
                        // If at least a collider is below the ball, abort reset
                        if (collider.Raycast(ray, out hit, Mathf.Infinity))
                        {
                            reset = false;
                            break;
                        }
                    }

                    if (reset)
                    {
                        Invoke("ResetBall", 0.5f);
                    }
                }
            }
        }
    }