Dear every,
I’m in the process of finishing my block breaker game, I have a little problem knowing when I set the collision on the bottom, the trigger is a gameover if the player has no life, a restart of the game (the ball is stuck paddle)
if he has any. the problem is that when I launch the ball () a music is triggered and in case of a second life of the player I launch the ball () again and it reproduces the music again, I end up with the same music in progress twice what to do please? voici mon code:
using UnityEngine;
using UnityEngine.SceneManagement;
public class Ball : MonoBehaviour
{
//config parameters
[SerializeField] Paddle paddleType;
[SerializeField] float xPush = 2f;
[SerializeField] float yPush = 75f;
[SerializeField] AudioClip[] BallSounds;
[SerializeField] AudioClip LevelOST;
[SerializeField] float RandomFactor;
// cached reference
AudioSource audiosource;
Rigidbody2D rb;
//state
bool hasStarted = false;
Vector2 paddleToBallVector;
void Start()
{
paddleToBallVector = transform.position - paddleType.transform.position;
audiosource = GetComponent<AudioSource>();
rb = GetComponent<Rigidbody2D>();
}
void Update()
{
if (!hasStarted)
{
LockBallToPaddle();
LaunchBallToPaddle();
}
}
private void LaunchBallToPaddle()
{
if(Input.GetMouseButtonDown(0))
{
hasStarted = true;
rb.velocity = new Vector2(xPush, yPush);
AudioClip clip = LevelOST;
audiosource.PlayOneShot(clip);
}
}
private void LockBallToPaddle()
{
hasStarted = false;
Vector2 paddlePos = new Vector2(paddleType.transform.position.x, paddleType.transform.position.y);
transform.position = paddleToBallVector + paddlePos;
}
private void OnCollisionEnter2D(Collision2D collision)
{
Vector2 VelocityTweak = new Vector2(Random.Range(0f, RandomFactor), Random.Range(0f, RandomFactor));
if (hasStarted)
{
AudioClip clip = BallSounds[UnityEngine.Random.Range(0, BallSounds.Length)];
audiosource.PlayOneShot(clip);
rb.velocity += VelocityTweak;
}
}
private void OnTriggerEnter2D(Collider2D other)
{
if(other.CompareTag("bottom"))
{
LockBallToPaddle();
//SceneManager.LoadScene("Game over");
}
}
}