コード例 #1
0
ファイル: BallController.cs プロジェクト: RSharma98/Pong2.0
    void OnCollisionEnter2D(Collision2D col)
    {
        //The position and size of the collision objects
        Vector2 colPos  = col.gameObject.transform.position;
        Vector2 colSize = col.gameObject.GetComponent <BoxCollider2D>().size *col.gameObject.transform.localScale;

        //If the ball hit the top or bottom of the object, flip the y velocity. Otherwise, flip the x velocity
        if (pos.y + size.y / 2 <= colPos.y - colSize.y / 2 || pos.y - size.y / 2 >= colPos.y + colSize.y / 2)
        {
            if (pos.x + size.x / 2 >= colPos.x - colSize.x / 2 && pos.x - size.x / 2 <= colPos.x + colSize.x / 2)
            {
                vel.y *= -1.05f;
            }
            else
            {
                vel.x *= -1.05f;
            }
        }
        else
        {
            vel.x *= -1.05f;
        }

        Color colour = col.gameObject.GetComponent <SpriteRenderer>().color;                            //Get the colour of the collision object

        GetComponent <SpriteRenderer>().color = colour;                                                 //Set the ball colour to the colour of the collision object
        trail.startColor = colour;                                                                      //Set the trail colour
        GameManager.instance.PlayHitParticles(col.transform.position, this.transform.position, colour); //Play the hit particles
        StartCoroutine(camController.Shake(0.1f));                                                      //Shake the camera

        if (col.gameObject.name.Contains("Paddle"))                                                     //If the ball hit a paddle
        {
            PaddleController paddleController = col.gameObject.GetComponent <PaddleController>();       //Get the paddle controller
            if (paddleController != null)                                                               //Make the ball move up or down depending on if the paddle had a positive or negative velocity
            {
                if (paddleController.GetVelocity().y > 0)
                {
                    vel.y = Mathf.Abs(vel.y);
                }
                else if (paddleController.GetVelocity().y < 0)
                {
                    vel.y = Mathf.Abs(vel.y) * -1;
                }
            }
        }
    }
コード例 #2
0
    private void AddPaddleVelocityToBall(PaddleController paddle)
    {
        float xVelocity = rigidbody2D.velocity.x;
        float yVelocity = paddle.GetVelocity().y;

        /*
         *  Make sure to explain normalisation of vectors
         *  This is to ensure that ball only ever has a speed based on speed we set in our variable
         */
        Vector3 newVelocity = new Vector3(xVelocity, yVelocity);

        newVelocity          = newVelocity.normalized;
        newVelocity         *= speed;
        rigidbody2D.velocity = newVelocity;
    }