Hi,
I am trying to give lives to the player for my block breaker game, when I die it takes a live away but the ball does not return back to the paddle. can someone help me with this? I would really appreciate it. my code is below:
using UnityEngine;
using UnityEngine.UI;
public class Ball : MonoBehaviour
{
//Configuration paremeters
[SerializeField] Paddle paddle1;
[SerializeField] float xPush = 2f; // this and the following is the paremeters of how high and how much to the side the ball starts after jump
[SerializeField] float yPush = 15f;
[SerializeField] AudioClip ballsounds; //this is for the audio purpose so it plays the sounds throughout the game different sounds per click
[SerializeField] float randomFactor = 0.2F; //this is to make ball bounce away from y and x axis so it moves away from the walls and towards the blocks
//the following code is connect lives to ball
public GameSession gs;
//following code is to connect loosecollider
public LooseCollider lc;
// State
Vector2 paddleToBallVector;
bool hasStarted = false; //This code is to let system know to release ball after click on mouse
//Cache component References
AudioSource myAudioSource; //this is to add music and let it play in all screens
Rigidbody2D myRigidBody2D;
void Start()
{
paddleToBallVector = transform.position - paddle1.transform.position; //this code is for the paddle to ball vector which is current position of ball with paddle position
myAudioSource = GetComponent<AudioSource>(); //this is telling system to go find the audio component and play it to play all different with only one code
myRigidBody2D = GetComponent<Rigidbody2D>();
}
// Update is called once per frame
void Update()
{
if (!hasStarted) //This code is let system know that once we click the mouse it must released the ball
{
LockBallToPaddle();
LaunchOnMouseClick();
}
}
private void LaunchOnMouseClick()
{
if (Input.GetMouseButtonDown(0))
{
hasStarted = true;
//The followign code is to click on mouse and will allow for ball to jump off a little to the side and upwards.
myRigidBody2D.velocity = new Vector2(xPush, yPush);
}
}
private void LockBallToPaddle()
{
Vector2 paddlePos = new Vector2(paddle1.transform.position.x, paddle1.transform.position.y);
transform.position = paddlePos + paddleToBallVector;
}
//the following code is to let system know when it collides with blocks it will make the music sound
private void OnCollisionEnter2D(Collision2D collision)
{
Vector2 velocityTweak = new Vector2(Random.Range(0f, randomFactor), Random.Range(0f, randomFactor));
if (hasStarted) //this code is to let system know that if the ball is in the paddle dont make the click music []this two brackets are arrays
{
AudioClip Clip = ballsounds[UnityEngine.Random.Range(0, ballsounds.Length)];
myAudioSource.PlayOneShot(Clip);
myRigidBody2D.velocity += velocityTweak;
}
}
}