I’m making a 2d pong game on unity but my problem is that if the ball touches the vertical sides I can’t get the goal to be scored and restart the game, in fact the ball instead of returning to midfield continues to move, can anyone help me please? Thank you so much!!
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class BallMovement : MonoBehaviour
{
[SerializeField] private float initialSpeed = 10;
[SerializeField] private float speedIncrease = 0.25f;
[SerializeField] private Text playerScore;
[SerializeField] private Text AIScore;
private int hitCounter;
private Rigidbody2D rb;
private int player1Score;
private int aiScore;
// Start is called before the first frame update
void Start()
{
rb = GetComponent<Rigidbody2D>();
Invoke("StartBall", 2f);
}
// Update is called once per frame
private void FixedUpdate()
{
rb.velocity = Vector2.ClampMagnitude(rb.velocity, initialSpeed + (speedIncrease * hitCounter));
}
private void StartBall()
{
rb.velocity = new Vector2(-1, 0) * (initialSpeed + speedIncrease * hitCounter);
}
private void ResetBall()
{
Debug.Log("Vamo raga forza Giuve Siuuuum");
rb.velocity = new Vector2(0, 0);
transform.position = new Vector2(0, 0);
hitCounter = 0;
Invoke("StartBall", 2f);
}
private void PlayerBounce(Transform myObject)
{
hitCounter++;
Vector2 ballPos = transform.position;
Vector2 playerPos = myObject.position;
float xDirection, yDirection;
if(transform.position.x > 0)
{
xDirection = -1;
}
else
{
xDirection = 1;
}
yDirection = (ballPos.y - playerPos.y) / myObject.GetComponent<Collider2D>().bounds.size.y;
if (yDirection == 0)
{
yDirection = 0.25f;
}
rb.velocity = new Vector2(xDirection, yDirection) * (initialSpeed + (speedIncrease *hitCounter));
}
private void OnCollisionEnter2D(Collision2D collision)
{
if(collision.gameObject.name == "Player" || collision.gameObject.name == "AI")
{
PlayerBounce(collision.transform);
}
}
private void OnTriggerEnter2D(Collider2D collision)
{
if(transform.position.x > 0)
{
Debug.Log("Siuum");
ResetBall();
player1Score++;
playerScore.text = player1Score.ToString();
}
else if(transform.position.x < 0)
{
Debug.Log("Gerry Scotti");
ResetBall();
aiScore++;
AIScore.text = aiScore.ToString();
}
}
}