using System.Collections; using System.Collections.Generic; using UnityEngine; public class Ball : MonoBehaviour { private float speed = 15; public string winner = ""; protected int playerOneScore, playerTwoScore = 0; /// /// responsible for calc /// the ball hit dir /// /// the ball position protected float hitFactor(Vector2 ballPos, Vector2 racketPos, float racketHeight) { return (ballPos.y - racketPos.y) / racketHeight; } /// /// responsible for ball reaction /// depending on the gameobj hit /// protected void BallReaction(Collision2D col, int x) { float y = hitFactor(transform.position, col.transform.position, col.collider.bounds.size.y); Vector2 dir = new Vector2(x, y).normalized; GetComponent().velocity = dir * speed; } /// /// /// /// /// /// protected void WinAction(Collision2D col, string winner, Vector2 side) { Debug.Log("The goal is scored by " + winner); Debug.Log(playerOneScore + ":" + playerTwoScore); GetComponent().velocity = side * speed; } // Start is called before the first frame update void Start() { GetComponent().velocity = Vector2.right * speed; } private void Update() { } /// /// Changes the pos of the ball /// when hit the racket /// void OnCollisionEnter2D(Collision2D col) { string objName = col.gameObject.name; switch (objName) { case "Racket_Left": BallReaction(col, 1); break; case "Racket_Right": BallReaction(col, -1); break; case "Wall_Left": winner = "Player 2"; playerTwoScore++; Vector2 right = Vector2.right; WinAction(col, winner, right); break; case "Wall_Right": winner = "Player 1"; playerOneScore++; Vector2 left = Vector2.left; WinAction(col, winner, left); break; default: break; } } }