Last time, we talked about the importance of sounds in video games and how they increase the immersion of the player; we also took a look at Unity’s sound system and even “pre-optimised” our sound file imports to avoid consuming too much memory. In this second part, we’ll focus on how to actually implement the sound system. So we’re going to see how to play some background music, global and local ambient sounds and contextual sounds like unit responses.

Note: I’ve embedded some videos with sound in this article to show our progress as we code the feature, but the quality of the sound recording isn’t very high — sorry in advance!

Preliminary step: moving the listener to a “ground target”

In part one of this duo of episodes, I mentioned that we had to tinker with the default listener setup a bit. Unity assumes that, in most of scenes, the camera is the representation of the player in the virtual world, position-wise. So it makes sense to use this object as the audio listener, especially for all the 3D audio sources.

However, in our RTS game, there is actually an offset between the actual point we are looking at (the 3D point on the ground that is the projection of the 2D point in the middle of the screen) and the position of the camera (up there in the sky, looking down at the ground). Thus we need to account for this difference and rather than keeping the listener on the camera, we need to place it on the ground.

The problem is that, for now, this point is completely abstract — we don’t actually have an object in our scene at that position. So let’s add a new “GroundTarget” empty game object as a child of our camera and add an AudioListener on it:

Remember that we also need to remove the current one from the camera.

Now, we can pass a reference to this “GroundTarget” in the CameraManager class and simply update its position when we set up the camera, and whenever it later moves:

Alright, we have a “cursor” that tracks where the camera is looking. This point will be used to compute the distance to 3D audio sources, as we’ll see soon with the local ambient sounds.

#unity #development #csharp #games

Making a RTS game #17: Introducing a sound system 2/2 (Unity/C#)
1.50 GEEK