Support 3D Spatial Audio Effects

Wouldn’t it be neat to have the background music get louder as the player approaches the exit? (Yeah, I thought so, too.) One of the neat things you can do with SpriteKit and the SKAudioNode class is support 3D spatial audio effects, such as using positional sound based on where a listener node is located.

The listener node is an instance property on an SKScene object. Typically, you’d set the camera or player node to be the scene’s listener. In Val’s Revenge, you’ll set the player node as the listener.

Switch to the GameScene.swift file. Below the setupPlayer() method, add the following code:

 func​ ​setupMusic​() {
 let​ musicNode = ​SKAudioNode​(fileNamed: ​"music"​)
  musicNode.isPositional = ​false
 
 // Make the audio node positional
 // so that the music gets louder as
 // the player gets closer to the exit
 if​ ​let​ exit = ​childNode​(withName: ​"exit"​) {
  musicNode.position = exit.position
  musicNode.isPositional = ​true
  listener = player
  }
 
 addChild​(musicNode)
 }

This code first makes sure there’s an exit node available within the scene. If so, it sets the position of the SKAudioNode object to match the exit node. It also sets the player node to the scene’s listener.

Of course, you’ll need to call this method from somewhere, and because you’re relying on the player node to exist, it makes sense to call it from the setupPlayer() method. Add the following code to the setupPlayer() method:

 setupMusic​()

Build and run the project. Notice how when you get closer to the exit, the music gets louder, and when you get farther away, so does the sound of the music.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset