indiegamedev

Unity3D – Game Engine – Stop and Resume Timer – JavaScript

Unity3D – Game Engine – Stop and Resume Timer – JavaScript

A Stop and Resume Timer is very useful in video games!

Create an Empty Object and assign Timer.js:


#pragma strict

var myTimer : float; // start value for the timer
var defTime : int; // the reset value
var isCounting : boolean = false; // true while time running
var countUp : boolean = false; // false to count 10...9...8...7...6 true to count 0...1...2...3...4
var GuiText : GUIText; // display timer values

function Start () {
}// END Start()

function Update () {
	Timer();
}// END Update()

function Timer() {
	if(myTimer <= 0){
			myTimer = 0.0; // we do not need negative time!
		}

		if(isCounting && !countUp){
			myTimer -= Time.deltaTime; // count 10...9...8...7...6
		}
			
		if(isCounting && countUp){
			myTimer += Time.deltaTime; // count 0...1...2...3...4
		}

		if(Input.GetKeyDown(KeyCode.R)){ // Reset at defTime
			myTimer = defTime;
		}

		if(Input.GetKeyDown(KeyCode.S)){ // start or stop timer
			isCounting = !isCounting; // invert value of isCounting boolean variable
		}

		GuiText.text = myTimer.ToString("F0"); // display timer values
	}//END Timer()

Inspector> DRAG AND DROP a ‘GUI Text’ over the var GuiText

Inspector> setup var myTimer= 10, var countUp= uncheck, it will count 10…9…8…7…6
OR
Inspector> setup var myTimer= 0, var countUp= check, it will count 0…1…2…3…4

Play, S to start and stop, R to reset.

By |Unity3D, Video Games Development|Commenti disabilitati su Unity3D – Game Engine – Stop and Resume Timer – JavaScript

Unity 3D – Loading and Downloading Screen – Basic

Unity 3D – Loading and Downloading Screen – Basic

Loading Screen

How to create a simple Loading Screen and using it with the Web Player

Create e scenes:

– level2 (it is the second scene)
– Main Camera
– Plane
-> attach a 4 MPix Texture
-> select the Texture> Inspector> Override for Web>
– Max Size 4096
– Format True Color
(it will be 20 MB into final build)

– level1 (it is the first scene)
– Main Camera
-> attach ‘GameController.js’
– Plane
-> attach a small Texture with a loading message
-> attach ‘LoadingScreen.js’
– GUI Text
-> attach ‘DownloadingText.js’

DownloadingText.js

#pragma strict

	// Attach this script to a GuiText object
	// Print on a guiText how much has been streamed level at index 1
	// When finished streaming, print "Level 1 has been fully streamed!"
	var percentageLoaded : float = 0;
	
	function Start () {

	}// ENd Start()
	function Update() {
		if(Application.GetStreamProgressForLevel(1) == 1) {
			guiText.text = "Level at index 1 has been fully streamed!";
		} else {
			percentageLoaded = Application.GetStreamProgressForLevel(1) * 100;
			guiText.text = percentageLoaded.ToString();// it displays: 54.569856... 100, you can use it to drive a progress bar!
		}
	}// END Update

GameController.js:

#pragma strict

function Start () {
}// END Start

function Update () {
}// END Update()

function OnGUI () {
    if (GUI.Button (Rect (10,10,150,100), "Load Next Level")) {
        Application.LoadLevel ("level2");          
    }
}// END OnGUI()

LoadingScreen.js

#pragma strict

function Start () {
	// Hide the object
	renderer.enabled = false;
}// END START

function Update () {
     //  It checks if the application is loading a level. If yes, then show the splash screen.
 	 if(Application.isLoadingLevel)
      Show();
}// END Update

function Show () {
	// Show the object
	renderer.enabled = true;
}// END Show()

MAIN TOP MENU> File> Build Settings>
– Scenes In Build> Add first level1.unity (0), then level2.unity(1)
– Platform Web Player
– Web Player> Streamed

Build, upload, play.

How does it work?
Really easy!
0. Watch the GUIText, with the percentage of download, you will see that web player is downloading level2.unity in background.
1. When the game starts the web player downloads level1.unity, after level2.unity and so on…
2. Press “Load Next Level”
3. NOTHING HAPPENS if the download of level2.unity is not complete.
4. ONLY when the download of level2.unity is completed, web player loading level2.unity scene
5. LoadingScreen.js checks if the application is loading a level. If yes, then show the splash screen.

Downloading Screen

For italian people:
‘Application.isLoadingLevel’ sarà TRUE solo nel momento in cui il livello sarà completamente scaricato e sarà iniziato il suo effettivo caricamento.
‘Application.isLoadingLevel’ NON ‘sente’ la fase di download della scena.

Per creare un loader durante lo streaming, prima dell’avvio dell’istruzione ‘Application.LoadLevel’ visualizzare una schermata di loading nella scena corrente. La procedura sarà:
1. Il livello1 viene terminato
2. Visualizzare una schermata per il download level2…
3. Avviare ‘Application.LoadLevel’ per iniziare il caricamento del livello2
4. Una volta scaricato completamente il livello2, inizierà il processo di caricamento del livello2
5. ‘Application.isLoadingLevel’ visualizzerà una schermata per il loading level2…
6. Il livello2 sarà avviato

Best streaming practice

50 KB display the logo and menu (4 seconds)
320 KB let the user play a tiny tutorial level or let him do some fun interaction in the menu (20 seconds)
800 KB let the user play the first small level (50 seconds)
Finish downloading the entire game within 1-5 MB (1-5 minutes)

Externalize the music and load it via the WWW class

Loads the level asynchronously in the background

Unity will completely load all assets and all objects in the scene in a background loading thread. You can create a completely streaming world where you constantly load and unload different parts of the world based on the player position.

Sample Code:

function Start () {
		// Load the level named "MyBigLevel".
		var async : AsyncOperation = Application.LoadLevelAsync ("MyBigLevel");
		yield async;
		Debug.Log ("Loading complete");
	}

Reference: http://docs.unity3d.com/ScriptReference/Application.LoadLevelAsync.html

By |Unity3D, Video Games Development|Commenti disabilitati su Unity 3D – Loading and Downloading Screen – Basic

Unity3D – Add Multiple Audio Sources – Javascript

Unity3D – Add Multiple Audio Sources – Javascript

Add Audio Sources to THIS GameObject – Advanced

1. Create a Empty Game Object and assign AddAudioSources.js:


#pragma strict

var myAudioClip : AudioClip[]; // Array of audio clips - fill it in Inspector
var mySources : AudioSource[]; // Array of audio souces
var nbOfSources : int; // Assign in Inspector the number of souces into array 
 
function Start()
{ 
    mySources = new AudioSource[nbOfSources]; // Create an Array of Audio Source
 
    for(source in mySources)// genera un array del tipo -> mySources[0].clip...
    {
        source = gameObject.AddComponent("AudioSource") as AudioSource;
    }
    
    // If you have 3 intems into array...
    mySources[0].clip = myAudioClip[0];
    mySources[1].clip = myAudioClip[1];
    mySources[2].clip = myAudioClip[2];
    
    // Others setup...
    mySources[0].playOnAwake = false; // not play in awake
    mySources[0].volume = 0.2; // setup volume
    mySources[0].Play(); // play the audio clip
 
}
	
function Update(){
	}

2. Inspector> AddAudioSources.js> AudioClip[]>Size, resize the array and DRAG AND DROP your .wav files into empty slots

3. Inspector> AddAudioSources.js> AudioSource[]>Size, resize the array

4. Play and watch inside Inspector> Empty Game Object

Add Audio Sources to ANOTHER GameObject

1. Create a Cube

2. Create a Empty Game Object and assign AddAudioSources.js:


#pragma strict

var myAudioClip : AudioClip[]; // Array of audio clips - fill it in Inspector
var mySources : AudioSource[]; // Array of audio souces
var nbOfSources : int; // Assign in Inspector the number of souces into array 
 
private var cubeobj : GameObject; // for find with name gameobject 
 
function Start()
{ 
    cubeobj = GameObject.Find("/Cube"); // Find gameobject with name

    mySources = new AudioSource[nbOfSources]; // Create an Array of Audio Source
 
    for(source in mySources)// genera un array del tipo -> mySources[0].clip...
    {
        source = cubeobj.AddComponent("AudioSource") as AudioSource;
    } 
}
	
function Update(){
	}

2. Inspector> AddAudioSources.js> AudioClip[]>Size, resize the array and DRAG AND DROP your .wav files into empty slots

3. Inspector> AddAudioSources.js> AudioSource[]>Size, resize the array

4. Play and watch inside Inspector> Cube

By |Unity3D, Video Games Development|Commenti disabilitati su Unity3D – Add Multiple Audio Sources – Javascript

Unity3D – CSharp Audio – Walking Footsteps

Unity3D – CSharp Audio – Walking Footsteps

First you have to consider:

– if character is grounded
– different audio clips depending of movement direction
– random pitch (velocità di riproduzione)
– random audio clips
– trigger zones for different ground surfaces
– trigger zones for different environments

1. In my oipinion the best practice is using an AnimationEvents to synch the Animation and the SFX (http://docs.unity3d.com/Manual/animeditor-AnimationEvents.html)

AnimationEvents -> will calls -> FootstepSfxScript.cs

2. Script some conditions:


using UnityEngine; 
using System.Collections;

public class FootSteps : MonoBehaviour {

	public CharacterController controller; 
	public AudioClip[] concrete ; 
	public AudioClip[] wood ; 
	public AudioClip[] dirt ; 
	public AudioClip[] metal ; 
	public AudioClip[] glass ; 
	public AudioClip[] sand; 
	public AudioClip[] snow; 
	public AudioClip[] floor; 
	public AudioClip[] grass;
	
	private bool step = true; 
	float audioStepLengthWalk = 0.45f; 
	float audioStepLengthRun = 0.25f;
	
	void OnControllerColliderHit ( ControllerColliderHit hit) {
		
		if (controller.isGrounded && controller.velocity.magnitude < 7 && controller.velocity.magnitude > 5 && hit.gameObject.tag == "Untagged" && step == true ) {
			WalkOnConcrete();
		} else if (controller.isGrounded && controller.velocity.magnitude > 8 && hit.gameObject.tag == "Concrete" && step == true || controller.isGrounded && controller.velocity.magnitude > 8 && hit.gameObject.tag == "Untagged" && step == true) {
			RunOnConcrete();
		} else if (controller.isGrounded && controller.velocity.magnitude < 7 && controller.velocity.magnitude > 5 && hit.gameObject.tag == "Wood" && step == true) {
			WalkOnWood();
		} else if (controller.isGrounded && controller.velocity.magnitude > 8 && hit.gameObject.tag == "Wood" && step == true) {
			RunOnWood();
		} else if (controller.isGrounded && controller.velocity.magnitude < 7 && controller.velocity.magnitude > 5 && hit.gameObject.tag == "Dirt" && step == true) {
			WalkOnDirt();
		} else if (controller.isGrounded && controller.velocity.magnitude > 8 && hit.gameObject.tag == "Dirt" && step == true) {
			RunOnDirt();
		} else if (controller.isGrounded && controller.velocity.magnitude < 7 && controller.velocity.magnitude > 5 && hit.gameObject.tag == "Metal" && step == true) {
			WalkOnMetal();
		} else if (controller.isGrounded && controller.velocity.magnitude > 8 && hit.gameObject.tag == "Metal" && step == true) {
			RunOnMetal();       
		} else if (controller.isGrounded && controller.velocity.magnitude < 7 && controller.velocity.magnitude > 5 && hit.gameObject.tag == "Glass" && step == true) {
			WalkOnGlass();
		} else if (controller.isGrounded && controller.velocity.magnitude > 8 && hit.gameObject.tag == "Glass" && step == true) {
			RunOnGlass();
		} else if (controller.isGrounded && controller.velocity.magnitude < 7 && controller.velocity.magnitude > 5 && hit.gameObject.tag == "Sand" && step == true) {
			WalkOnSand();
		} else if (controller.isGrounded && controller.velocity.magnitude > 8 && hit.gameObject.tag == "Sand" && step == true) {
			RunOnSand();            
		} else if (controller.isGrounded && controller.velocity.magnitude < 7 && controller.velocity.magnitude > 5 && hit.gameObject.tag == "Snow" && step == true) {
			WalkOnSnow();
		} else if (controller.isGrounded && controller.velocity.magnitude > 8 && hit.gameObject.tag == "Snow" && step == true) {
			RunOnSnow();
		} else if (controller.isGrounded && controller.velocity.magnitude < 7 && controller.velocity.magnitude > 5 && hit.gameObject.tag == "Floor" && step == true) {
			WalkOnFloor();
		} else if (controller.isGrounded && controller.velocity.magnitude > 8 && hit.gameObject.tag == "Floor" && step == true) {
			RunOnFloor();   
		} else if (controller.isGrounded && controller.velocity.magnitude < 7 && controller.velocity.magnitude > 5 && hit.gameObject.tag == "Grass" && step == true) {
			WalkOnGrass();
		} else if (controller.isGrounded && controller.velocity.magnitude > 8 && hit.gameObject.tag == "Grass" && step == true) {
			RunOnGrass();                   
			
		}       
	}
	
	IEnumerator WaitForFootSteps(float stepsLength) { step = false; yield return new WaitForSeconds(stepsLength); step = true; } 

/////////////////////////////////// CONCRETE //////////////////////////////////////// 
	/// 
void WalkOnConcrete() {
	
	audio.clip = concrete[Random.Range(0, concrete.Length)];
	audio.volume = 0.1f;
	audio.Play();
	StartCoroutine(WaitForFootSteps(audioStepLengthWalk));
}

void RunOnConcrete() {
	
	audio.clip = concrete[Random.Range(0, concrete.Length)];
	audio.volume = 0.3f;
	audio.Play();
	StartCoroutine(WaitForFootSteps(audioStepLengthWalk));
}

////////////////////////////////// WOOD ///////////////////////////////////////////// 

void WalkOnWood() {

audio.clip = wood[Random.Range(0, wood.Length)];
audio.volume = 0.1f;
audio.Play();
StartCoroutine(WaitForFootSteps(audioStepLengthWalk));
}

void RunOnWood() {
	
	audio.clip = wood[Random.Range(0, wood.Length)];
	audio.volume = 0.3f;
	audio.Play();
	StartCoroutine(WaitForFootSteps(audioStepLengthRun));
}

/////////////////////////////////// DIRT ////////////////////////////////////////////// 

void WalkOnDirt() {

audio.clip = dirt[Random.Range(0, dirt.Length)];
audio.volume = 0.1f;
audio.Play();
StartCoroutine(WaitForFootSteps(audioStepLengthWalk));
}

void RunOnDirt() {
	
	audio.clip = dirt[Random.Range(0, dirt.Length)];
	audio.volume = 0.3f;
	audio.Play();
	StartCoroutine(WaitForFootSteps(audioStepLengthRun));
}

////////////////////////////////// METAL /////////////////////////////////////////////// 

void WalkOnMetal() {

audio.clip = metal[Random.Range(0, metal.Length)];
audio.volume = 0.1f;
audio.Play();
StartCoroutine(WaitForFootSteps(audioStepLengthWalk));
}

void RunOnMetal() {
	
	audio.clip = metal[Random.Range(0, metal.Length)];
	audio.volume = 0.3f;
	audio.Play();
	StartCoroutine(WaitForFootSteps(audioStepLengthRun));
}

////////////////////////////////// GLASS /////////////////////////////////////////////// 

void WalkOnGlass() {

audio.clip = glass[Random.Range(0, glass.Length)];
audio.volume = 0.1f;
audio.Play();
StartCoroutine(WaitForFootSteps(audioStepLengthWalk));
}

void RunOnGlass() {
	
	audio.clip = glass[Random.Range(0, glass.Length)];
	audio.volume = 0.3f;
	audio.Play();
	StartCoroutine(WaitForFootSteps(audioStepLengthRun));
}

////////////////////////////////// SAND /////////////////////////////////////////////// 

void WalkOnSand() {

audio.clip = sand[Random.Range(0, sand.Length)];
audio.volume = 0.1f;
audio.Play();
StartCoroutine(WaitForFootSteps(audioStepLengthWalk));
}

void RunOnSand() {
	
	audio.clip = sand[Random.Range(0, sand.Length)];
	audio.volume = 0.3f;
	audio.Play();
	StartCoroutine(WaitForFootSteps(audioStepLengthRun));
}

////////////////////////////////// SNOW /////////////////////////////////////////////// 

void WalkOnSnow() {

audio.clip = snow[Random.Range(0, snow.Length)];
audio.volume = 0.1f;
audio.Play();
StartCoroutine(WaitForFootSteps(audioStepLengthWalk));
}

void RunOnSnow() {
	
	audio.clip = snow[Random.Range(0, snow.Length)];
	audio.volume = 0.3f;
	audio.Play();
	StartCoroutine(WaitForFootSteps(audioStepLengthRun));
}

////////////////////////////////// FLOOR /////////////////////////////////////////////// 

void WalkOnFloor() {

audio.clip = floor[Random.Range(0, floor.Length)];
audio.volume = 0.1f;
audio.Play();
StartCoroutine(WaitForFootSteps(audioStepLengthWalk));
}

void RunOnFloor() {
	
	audio.clip = floor[Random.Range(0, floor.Length)];
	audio.volume = 0.3f;
	audio.Play();
	StartCoroutine(WaitForFootSteps(audioStepLengthRun));
}

////////////////////////////////// GRASS /////////////////////////////////////////////// 

void WalkOnGrass() {

audio.clip = grass[Random.Range(0, grass.Length)];
audio.volume = 0.1f;
audio.Play();
StartCoroutine(WaitForFootSteps(audioStepLengthWalk));
}

void RunOnGrass() {
	
	audio.clip = grass[Random.Range(0, grass.Length)];
	audio.volume = 0.3f;
	audio.Play();
	StartCoroutine(WaitForFootSteps(audioStepLengthRun));
}

}// END class FootSteps

For italian people: come funziona?

1. Ottengo il Character Controller

public CharacterController controller; 

2. Inserisco in un array le clip sonore

public AudioClip[] wood ; 

3. Definisco la lunghezza delle clip

float audioStepLengthWalk = 0.45f; 
float audioStepLengthRun = 0.25f;

4. Verifico delle condizioni:

} else if (controller.isGrounded && controller.velocity.magnitude < 7 && controller.velocity.magnitude > 5 && hit.gameObject.tag == "Wood" && step == true) {
			WalkOnWood();
} else if (controller.isGrounded && controller.velocity.magnitude > 8 && hit.gameObject.tag == "Wood" && step == true) {			RunOnWood();

– controller.isGrounded -> controllo che il controller sia a terra
– controller.velocity.magnitude < 7 -> la velocità del controller sul piano xz, se bassa stà camminando, se più alta sta correndo
– hit.gameObject.tag == “Wood” -> il tipo di terreno che il controller sta toccando
– step == true -> la variabile step è vera

5. Richiama la funziona specifica

void WalkOnWood() {

audio.clip = wood[Random.Range(0, wood.Length)]; // seleziona casualmente l'audio prelevandolo dall'array
audio.volume = 0.1f; // da un volume, basso possibilmente
audio.Play(); // play l'audio
StartCoroutine(WaitForFootSteps(audioStepLengthWalk));// avvia Couroutine per evitare la riproduzione continua
}

6. La Coroutine per riprodurre il suono

IEnumerator WaitForFootSteps(float stepsLength) { step = false; yield return new WaitForSeconds(stepsLength); step = true; } 

– WaitForFootSteps(float stepsLength) -> riceve la lunghezza della clip
– step = false -> interrompe la condizione -> if (controller.isGrounded … && step == true)
– yield return new WaitForSeconds(stepsLength) -> attende fino alla fine della riproduzione del suono
– step = true; -> fa ripartire la condizione if

By |Unity3D, Video Games Development|Commenti disabilitati su Unity3D – CSharp Audio – Walking Footsteps

Unity3D – Play a sound in sync with a countdown

Unity3D – Play a sound in sync with a countdown

Create a scene with:

– Main Camera

– Cube, attach the script:


#pragma strict

// AudioCountDown() variables START ################################################################
var pinPulled : boolean = false;
var fuse : float = 8.5; // the grenade explodes x seconds after the pin is pulled
var fuseTimer : float = 0;
var grenadeBeep : AudioClip;
var slowInterval : float = 1.0; // slow speed SFX
var fastInterval : float = 0.2; // fast speed SFX for last seconds
private var nextTime : float = -1; // declare this variable outside any function so every function can acces 
// AudioCountDown() variables END ##################################################################

function Start () {
} // END Start

function Update () {
		AudioCountDown();// call the audio for the CountDown	
}// END Update

function OnMouseDown ()
{
        // When you click over the object
        pinPulled = true; // the grenade pin will be pulled
        Debug.Log('Pin Pulled!');
}// END OnMouseDown()

function AudioCountDown(){
	// Audio CountDown START ##################################################################
	//If a grenade's pin has been pulled, start the countdown
	if (pinPulled) {
	   fuseTimer -= Time.deltaTime;
	}
	else { // pin in place: reset fuseTimer and nextTime
	   fuseTimer = fuse;
	   nextTime = fuseTimer - slowInterval; // set time for 1st tick
	}
	 
	if (fuseTimer <= nextTime) { // it's time to tick:
	   if (fuseTimer < 3.0){ // if entered fast range (last second), use fast interval
	       nextTime -= fastInterval;
	   } else { // otherwise beep at slow interval
	       nextTime -= slowInterval;
	   }
	   audio.clip = grenadeBeep;
	   audio.Play(); // call Play only once
	}
	// Audio CountDown END  ####################################################################
}// END AudioCountDown()

Inspector> DRAG AND DROP the Bomb-Detonator SFX over var grenadeBeep

Play, click over the cube to start the SFX CountDown

For italian people: come funziona?
1. la variabile pinPulled viene settata true, corrisponde al togliere la sicura alla granata

2. fuseTimer è il conto alla rovescia che si attiva se pinPulled è true infatti:


//If a grenade's pin has been pulled, start the countdown
	if (pinPulled) {
	   fuseTimer -= Time.deltaTime;
	}
	else { // pin in place: reset fuseTimer and nextTime
	   fuseTimer = fuse;
	   nextTime = fuseTimer - slowInterval; // set time for 1st tick

3. fuseTimer una volta attivato viene scalato di 1 secondo alla volta

fuseTimer -= Time.deltaTime;

4. se è passato almeno un secondo…

if (fuseTimer <= nextTime)

5. avvia l’effetto sonoro

           audio.clip = grenadeBeep;
	   audio.Play(); // call Play only once

6. se il countdown è agli ultimi 3 secondi il suono sarà emesso più velocemente

if (fuseTimer <= nextTime) { // it's time to tick:
	   if (fuseTimer < 3.0){ // if entered fast range (last second), use fast interval
	       nextTime -= fastInterval;
By |Unity3D, Video Games Development|Commenti disabilitati su Unity3D – Play a sound in sync with a countdown