# Play Sound when turret rotates

Hello,

Thanks for reading. Having some difficulty getting a sound to play when a turret rotates. At present, the sound plays continually when an enemy is near, i.e. even if the turret’s barrel is perfectly aligned with the target.

Here’s the code for turret rotation:

``````        // Plays the sound of turret rotating
PlayRotateTurretSound();

// Get the distance to the enemy
float distanceToEnemy = Vector3.Distance(targetPosition, transform.position);
Debug.Log ("TurretGunScript.RotateTurret: Distance to enemy : " + distanceToEnemy);

// Get the amount of time it will take for bullet to hit enemy
float timeToHit = distanceToEnemy/bulletSpeed;
Debug.Log ("TurretGunScript.RotateTurret: Bullet travel time : " + timeToHit);

// Get the velocity of the target rigidbody and multiply by amount of time to hit
Vector3 targetVelocity = (target.rigidbody.velocity * timeToHit) * 1.5f; // This compensates for some descrepancy, presumably in bulletSpeed

// Add the velocity * time to the target's curret position
Vector3 finalPos = targetPosition + targetVelocity;

// Get the direction to aim the turret
Vector3 aimDirection = finalPos - bulletSpawn0.transform.position;

// Rotate turret to face that position
Quaternion neededRotation = Quaternion.LookRotation(aimDirection);
transform.rotation = Quaternion.Slerp(transform.rotation, neededRotation, rotationSpeed * Time.deltaTime);
``````

I’m guessing this could be achieved by using an if statement around the instruction to play the sound, and requiring a minimum change in direction to the target, but I’m a little weak on angles and quaternions, and don’t know how to do this. Any help greatly appreciated.

One good solution to this would be to store the transform.rotation before you apply the Slerp, then compare the new transform.rotation with the stored one (using ==) and see if they are different; if so, play the sound.

See if you can work up the new script for this. If you get stuck, post your new script, and I’ll help you a bit more.

Edit: another solution, even better, would be to compare “neededRotation” with Quaternion.identity before you call the slerp. If they’re NOT equal, then do the rotation and play the sound. I’m not that familiar with Quaternions, but this should work. Try this solution, and if it doesn’t work then try the one above.