Exemple #1
0
    private void OnTriggerEnter2D(Collider2D collision)
    {
        if (collision.gameObject.CompareTag("PlayerGoal"))
        {
            scoreTracker.incrementOpponentScore();
            ResetBall();
        }
        if (collision.gameObject.CompareTag("OpponentGoal"))
        {
            scoreTracker.incrementPlayerScore();
            ResetBall();
        }

        if (collision.gameObject.CompareTag("Paddle"))
        {
            numberOfBounces++;

            var speedToAdd = 0f;
            if (numberOfBounces == 8)
            {
                speedToAdd = rainbowRushAddedSpeed;
            }

            if (numberOfBounces >= 8)
            {
                shakeElapsedTime = shakeDuration;
            }

            var hitSoundEffect = paddleHitClips[harmonyGenerator.NextNote()];
            audio.PlayOneShot(hitSoundEffect, 1);

            var collisionPoint           = collision.ClosestPoint(rb2d.position);
            var distanceFromPaddleCentre = collisionPoint.y - collision.attachedRigidbody.position.y; // positive or negative
            var collisionPointPortion    = distanceFromPaddleCentre / collision.bounds.size.y;        // value between -0.5 and 0.5

            var newVelocityXSign = collision.transform.position.x < rb2d.position.x ? 1 : -1;

            var velocityAngle = collisionPointPortion * Mathf.PI * angleWideness;
            var newVelocityX  = Mathf.Cos(velocityAngle);
            var newVelocityY  = Mathf.Sin(velocityAngle);
            var newSpeed      = rb2d.velocity.magnitude + speedToAdd;
            rb2d.velocity = new Vector2(newVelocityX * newVelocityXSign, newVelocityY) * newSpeed;
        }
    }