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;
/// <summary>
/// responsible for calc
/// the ball hit dir
/// </summary>
/// <returns>the ball position</returns>
protected float hitFactor(Vector2 ballPos, Vector2 racketPos, float racketHeight)
{
return (ballPos.y - racketPos.y) / racketHeight;
}
/// <summary>
/// responsible for ball reaction
/// depending on the gameobj hit
/// </summary>
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<Rigidbody2D>().velocity = dir * speed;
}
/// <summary>
///
/// </summary>
/// <param name="col"></param>
/// <param name="winner"></param>
/// <param name="side"></param>
protected void WinAction(Collision2D col, string winner, Vector2 side)
{
Debug.Log("The goal is scored by " + winner);
Debug.Log(playerOneScore + ":" + playerTwoScore);
GetComponent<Rigidbody2D>().velocity = side * speed;
}
// Start is called before the first frame update
void Start()
{
GetComponent<Rigidbody2D>().velocity = Vector2.right * speed;
}
private void Update()
{
}
/// <summary>
/// Changes the pos of the ball
/// when hit the racket
/// </summary>
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;
}
}
}