Skip to content
tukapai edited this page May 13, 2016 · 1 revision

The necessary implementation as the game already has almost terminated in the before chapter.

this chapter, implement a sound when it exploded, shot player and BGM.

8.1 Attuch BGM

3D Sound

To simulate the effects of position, Unity requires sounds to originate from Audio Sources attached to objects. The sounds emitted are then picked up by an Audio Listener attached to another object, most often the main camera. Unity can then simulate the effects of a source’s distance and position from the listener object and play them to the user accordingly. The relative speed of the source and listener objects can also be used to simulate the Doppler Effect for added realism.

Drag and drop bgm files to scene view.

Select bgm GameObject and check Loop in inspector.

Please be careful about volume Play game scene. It should be BGM is reproduced with a game start.

8.2 Attuch shot sound

Implement a shot sound when a player shoot a bullet.

Attach Audio Source component and set a necessary parameter.

Use Audio Clip in Sound/SE shoot.

Check is off in Play On Awake, change volume 0.3 and Pitch 0.64

Play shot sound from script.

Player.cs

using UnityEngine;
using System.Collections;

public class Player : MonoBehaviour
{
	// Spaceship component
	Spaceship spaceship;
	
	IEnumerator Start ()
	{
		// Get Spaceship component
		spaceship = GetComponent<Spaceship> ();
		
		while (true) {
			
			// Shot bullet same position and direction ShotPosition
			spaceship.Shot (transform);
			
			// Play shot sound
			GetComponent<AudioSource>().Play();
			
			// wait shotDelay/sec
			yield return new WaitForSeconds (spaceship.shotDelay);
		}
	}
	
	void Update ()
	{
		// Right,left
		float x = Input.GetAxisRaw ("Horizontal");
		
		// Up,down
		float y = Input.GetAxisRaw ("Vertical");
		
		// Move direction
		Vector2 direction = new Vector2 (x, y).normalized;
		
		// Move
		spaceship.Move (direction);
	}
	
	// Call back when collide
	void OnTriggerEnter2D (Collider2D c)
	{
		// Get layer name
		string layerName = LayerMask.LayerToName(c.gameObject.layer);
		
		// Erase bullet when layer name Bullet(Enemy)
		if( layerName == "Bullet (Enemy)")
		{
			// Erase Bullet
			Destroy(c.gameObject);
		}
		
		// Explosion when layer name Bullet(Enemy) or Enemy
		if( layerName == "Bullet (Enemy)" || layerName == "Enemy")
		{
			// Explosion
			spaceship.Explosion();
			
			// Destroy Player
			Destroy (gameObject);
		}
	}
}

Play game scene, It should ring shot sound while player shooting.

8.3 attach explosion sound

Implement an explosion when it exploded.

Attach Explosion sound Sounds/SE boom to Explosion prefab.

It should be ring explosion sound when explode.

Finish part of 8

This part is finished. If you get stuck, Download below project file and go next part.

Download project file

Clone this wiki locally