I want whenever my ball hits the paddle a specific sound should come, but not when I didn’t launch the ball. How to do that ? I was trying, but I stuck in here. Help me correct please.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Paddle : MonoBehaviour
{
[SerializeField] float screenWidthInUnits = 16f;
[SerializeField] float minX = 1f;
[SerializeField] float maxX = 15f;
[SerializeField] AudioClip hitSound;
bool hasStarted = false;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
float mousePosInUnits = Input.mousePosition.x / Screen.width * screenWidthInUnits;
Vector2 paddlePos = new Vector2(mousePosInUnits, transform.position.y);
paddlePos.x = Mathf.Clamp(mousePosInUnits, minX, maxX);
transform.position = paddlePos;
if (!hasStarted)
{
PlayOnMouseClick;
}
}
private void PlayOnMouseClick()
{
if (Input.GetMouseButtonDown(0))
{
hasStarted = true;
AudioSource.PlayClipAtPoint(hitSound, Camera.main.transform.position);
}
private void OnCollisionEnter2D(Collision2D collision)
{
AudioSource.PlayClipAtPoint(hitSound, Camera.main.transform.position);
}
}