How can i play a shooting sound clip every time the guns make rotation ?

his is the guns i have that i rotate using the mouse press to speed up the rotation and when leaving the mouse button it slow down the rotation.

And image of the Inspector part:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class RotateGuns : MonoBehaviour
{
    public float rotationSpeedMin = 90;
    public float rotationSpeedMax = 180;
    public float currentSpeed = 0;
    public float acceleration = 10;

    private void Update()
    {
        if (Input.GetMouseButton(0))
        {
            // Rotate guns according to rate of fire bullets amount.
            if (currentSpeed < rotationSpeedMax)
            {
                currentSpeed += acceleration * Time.deltaTime;
            }
            transform.Rotate(Vector3.right * Time.deltaTime * currentSpeed);
        }
        else
        {
            if (currentSpeed > rotationSpeedMin)
            {
                currentSpeed -= acceleration * Time.deltaTime;
            }
            transform.Rotate(Vector3.right * Time.deltaTime * currentSpeed);
        }
    }
}

Now i added to the GameObject also a Audio Source component and added a audio clip to the AudioClip.

When i’m running the game it’s playing the audio clip once automatic.

But what i want is to play the audio clip each time the guns rotating and to play it in speed according to the rotating speed.

Where should i and how should i play the audio clip according to when the guns are rotating and according to the rotating speed ?

I’d separate my data from the display…

Create a variable for the current position, update it, and when it crosses the boundary I’d play the audio.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class RotateGuns : MonoBehaviour
{
    public float rotationSpeedMin = 90f;
    public float rotationSpeedMax = 180f;
    public float acceleration = 10f;
    public float deceleration = 10f;
    public AudioSource audio;
    public AudioClip clip;
   
    private float _currentSpeed = 0f;
    private float _currentPosition = 0f;

    private void Update()
    {
        if (Input.GetMouseButton(0))
        {
            _currentSpeed = Mathf.Clamp(_currentSpeed + acceleration * Time.deltaTime, rotationSpeedMin, rotationSpeedMax);
        }
        else
        {
            _currentSpeed = Mathf.Clamp(_currentSpeed - deceleration * Time.deltaTime, rotationSpeedMin, rotationSpeedMax);
        }
       
        _currentPosition += currentSpeed;
        if(_currentPosition > 360f)
        {
            //modulo will work somewhat like subtraction, but if for whatever reason it accelerated so fast that you got to 725 degrees for instance, you'd still get 5.
            _currentPosition = _currentPosition % 360f;
            audio.PlayOneShot(clip);
        }
        transform.localRotation = Quaternion.Euler(_currentPosition, 0f, 0f);
    }
}
1 Like