I decided to give my touch to the code using what was previously shown, I wasn’t very happy with the fact that the ball would always be launching in the same direction on the X-axis, I added the Randon.range method to have more randomness in the game.
Let me know if you know other ways or even a better way.
public class Ball : MonoBehaviour
{// config parms
[SerializeField] Paddle paddle1;
float xRandom;
[SerializeField] float yPush = 16f;
// state
UnityEngine.Vector2 paddleToBallVector;
bool hasStarded = false;
// Start is called before the first frame update
void Start()
{
paddleToBallVector = transform.position - paddle1.transform.position;
Xrandomness();
}
// Update is called once per frame
void Update()
{
if (!hasStarded)
{
LockBallToPaddle();
LaunchOnClick();
}
}
private void LaunchOnClick()
{
if (Input.GetMouseButtonDown(0))
{
hasStarded = true;
GetComponent<Rigidbody2D>().velocity = new UnityEngine.Vector2(xRandom, yPush);
}
}
private void LockBallToPaddle()
{
UnityEngine.Vector2 paddlepos = new UnityEngine.Vector2 (paddle1.transform.position.x, paddle1.transform.position.y);
transform.position = paddlepos + paddleToBallVector;
}
void Xrandomness()
{
xRandom = Random.Range(-7f, 8f);
}
}