videogames development

Unity – Spaceship Shooting Game – JS – Game Controller

Unity – Spaceship Shooting Game – JS – Game Controller

1. MAIN TOP MENU> GameObject> Create Empty> rename it ‘Game Controller’
2. Inspector> Transform> small gear icon> Reset
3. Inspector> Assign the tag GameController

Generate a single asteroid

4. Assign the cript ‘GameController.js’

#pragma strict

var hazard : GameObject;   // oggetto pericoloso - Assign the asteroid prefab inside Inspector
var spawnValues : Vector3; // Assign the max value of asteroid Vector3 position inside Inspector example X=6 Z=16

function Start () {
    SpawnWaves ();
}

function SpawnWaves () {
    // Asteroid position, Random values: X -6 to 6 | Z 16 to -16
    var spawnPosition : Vector3= new Vector3 (Random.Range (-spawnValues.x, spawnValues.x), spawnValues.y, spawnValues.z);
    // Asteroid rotation
    var spawnRotation : Quaternion= Quaternion.identity;
    // Render the hazard
    Instantiate (hazard, spawnPosition, spawnRotation);
}

Generate multiple asteroids

#pragma strict

// ######################### VARIABILI ASTEROIDI START ##################################
// Assegnare da Inspector il prefab Asteroid
var hazard : GameObject;  
// Assignare da Inspector la posizione nella quale può essere generato Asteroid, 
// per X=6, sarà uguale per X a +6 o -6 unità Unity dal centro 0,0,0  
var spawnValues : Vector3; 
// Assegnare da Inspector il numero di asteroidi per ondata da generare  
var hazardCount : int;
// Assegnare da Inspector il tempo di attesa nel generare i singoli asteroidi di un'ondata
var spawnWait : float;
// Assegnare da Inspector il tempo di attesa per generare il primo asteroide
// il giocatore avrà il tempo di concentrarsi prima di iniziare a giocare
var startWait : float;
// Assegnare da Inspector il tempo di attesa tra un'ondata e la successiva
var waveWait : float;
// ######################### VARIABILI ASTEROIDI END ####################################

function Start () {
    // Al'interno della funzione start richiamo la funzione per generare le ondate di asteroidi
    SpawnWaves ();
}

// FUNZIONE GENERAZIONE ONDATE ASTEROIDI START
function SpawnWaves () {
    // imposto una breve pausa per dare il tempo al giocatore di concentrarsi prima di iniziare a giocare
    yield WaitForSeconds (startWait);
    // GENERAZIONE ONDATE INIZIO - while sempre vero, genera un ciclo infinito di asteroidi
    while (true)
    {
        // Genera la singola ondata di asteroidi, il numero di asteroidi che compone l'ondata è la variabile hazardCount
        for ( var i : int= 0; i < hazardCount; i++)
        {
             var spawnPosition : Vector3= new Vector3 (Random.Range (-spawnValues.x, spawnValues.x), spawnValues.y, spawnValues.z);
             var spawnRotation : Quaternion= Quaternion.identity;
            Instantiate (hazard, spawnPosition, spawnRotation);
            // Tempo di attesa che trascorre tra la generazione di un asteroide e il successivo
            // per evitare che si scontrino tra loro
            yield WaitForSeconds (spawnWait);
        }
        yield WaitForSeconds (waveWait);
    }
    // GENERAZIONE ONDATE FINE - while sempre vero, genera un ciclo infinito di asteroidi
}
// FUNZIONE GENERAZIONE ONDATE ASTEROIDI END
By |Unity3D, Video Games Development|Commenti disabilitati su Unity – Spaceship Shooting Game – JS – Game Controller

Unity – Spaceship Shooting Game – JS – Asteroid

Unity – Spaceship Shooting Game – JS – Asteroid

1. Hierarchy> Asteroid (Empty Object)
– prop_asteroid_01, (3d model of Asteroid), child of Asteroid

Random Rotate

2.Hierarchy select Asteroid and assign this scripts:

RandomRotator.js

#pragma strict

// Ruzzolare
var tumble : float; // setup this variable inside Inspector

function Start () : void {
                             // Random.insideUnitSphere function give a random Vector 3 value
    rigidbody.angularVelocity = Random.insideUnitSphere * tumble; 
}

NOTICE: Random.insideUnitSphere function give a random Vector 3 value

Destroy

DestroyByContact.js

#pragma strict

// Destruction of asteroid START
function OnTriggerEnter(other : Collider) 
{
    // If there is a GameObject with Tag Boundary ignore it
    if (other.tag == "Boundary")
    {
        // Return and does not reach - Destroy - commands lines
        return;
    }
    // Else it destroies other GameObject and Itself
    Destroy(other.gameObject);
    Destroy(gameObject);
}
// Destruction of asteroid END

Destroy Advanced

DestroyByContact.js

#pragma strict

// Destruction of asteroid START
var explosion : GameObject;       // Assign GameObject inside Inspector
var playerExplosion : GameObject; // Assign GameObject inside Inspector

function OnTriggerEnter(other : Collider) 
{
    // If there is a GameObject with Tag Boundary ignore it
    if (other.tag == "Boundary")
    {
        // Return and does not reach - Destroy - commands lines
        return;
    }
    // Play explosion 
    Instantiate(explosion, transform.position, transform.rotation);
    // If there is a GameObject with Tag Player Play playerExplosion
    if (other.tag == "Player")
    {
        Instantiate(playerExplosion, other.transform.position, other.transform.rotation);
    }
    // Destroy other GameObject and Itself
    Destroy(other.gameObject);
    Destroy(gameObject);
}
// Destruction of asteroid END

Move

Mover.js

#pragma strict

var speed : float; // Assign this inside Inspector

function Start () : void {
    // forward is the Z Axis
    rigidbody.velocity = transform.forward * speed;
}

Prefab the asteroid

The Asteroid is ready to become a Prefab

1. Hierarchy> DRAG AND DROP ‘Asteroid’ inside Assets> ‘Prefab’ folder
2. Hierarchy> Asteroid> CANC to delete it

By |Unity3D, Video Games Development|Commenti disabilitati su Unity – Spaceship Shooting Game – JS – Asteroid

Unity – Spaceship Shooting Game – JS – Laser Bolt

Unity – Spaceship Shooting Game – JS – Laser Bolt

1. Create the Prefab ‘Bolt’
2. The prefabs needs inside Inspector:
– Transform
– Rigid Body
– Capsule Collider: check ‘Is Trigger’

– Mover.js

#pragma strict

var speed : float; // Assign this inside Inspector

function Start () : void {
    // forward is the Z Axis
    rigidbody.velocity = transform.forward * speed;
}

Inspector> Mover (Script)
– Speed: 20

3. Create a Prefab ‘Player’ (it is the spaceship)
4. Create an Empty Object ‘Shot Spawn’ (produttore di spari)
5. DRAG AND DROP ‘Shot Spawn’ over Hierarchy> ‘Player’, now ‘Shot Spawn’ is child of ‘Player’
6. DRAG AND DROP ‘Bolt Prefab’ over Hierarchy> ‘Shot Spawn’, now ‘Bolt Prefab’ is child of ‘Shot Spawn’

At the end the Hierarchy will be:

Player
– Shot Spawn
– Bolt Prefab

Assign to ‘Player’ PlayerController.js:

#pragma strict

class Boundary
{
    // Theese variables are public to make the code easy-reusable
    // You can setup theese variables from Inspector
    var xMin : float;
    var xMax : float;
    var zMin : float;
    var zMax : float;
}

var speed : float;
var tilt : float;
var boundary : Boundary;

var shot : GameObject;     // Inspector -> assign Bolt Prefab
var shotSpawn : Transform; // Inspector -> assign Shot Spawn Empty Object
var fireRate : float;      // Inspector -> 0.25 (seconds) = 4 shot per second

private var nextFire : float;

function Update () {
    // Get Input Fire button
    if (Input.GetButton("Fire1") && Time.time > nextFire)
    {
        nextFire = Time.time + fireRate;
        // Return the clone of the GameObject, position, rotation if user click Fire button 
        Instantiate(shot, shotSpawn.position, shotSpawn.rotation);
        // Assign an audio file inside Inspector
        audio.Play ();
    }
}

function FixedUpdate () {
     // Get User Input START
     var moveHorizontal : float= Input.GetAxis ("Horizontal");
     var moveVertical : float= Input.GetAxis ("Vertical");
     // Get User Input END

     // Move the GameObject
     var movement : Vector3= new Vector3 (moveHorizontal, 0.0f, moveVertical);
    rigidbody.velocity = movement * speed;

    // Limitate movement inside the screen START
    rigidbody.position = new Vector3 
    (
        Mathf.Clamp (rigidbody.position.x, boundary.xMin, boundary.xMax), 
        0.0f, 
        Mathf.Clamp (rigidbody.position.z, boundary.zMin, boundary.zMax)
    );
    // Limitate movement inside the screen END

    // Tilt movement START
    rigidbody.rotation = Quaternion.Euler (0.0f, 0.0f, rigidbody.velocity.x * -tilt);
    // Tilt movement END
}

Hierarchy> Player> Shot Spawn> Bolt CANC to delete
Se non si cancella questo oggetto, all’inizio del gioco la nostra astronave sparerà subito un colpo, invece noi vogliamo che non vengano emessi colpi fino a che il tasto fire resta inutilizzato.

7. MAIN tOP MENU> GameObject> Cube and name it ‘Boundary’
8. Hierarchy> select ‘Cube’> Inspector>
– Transform> small gear icon> Reset
– Mesh Render> uncheck
– Box Collider> check ‘Is Trigger’
9. Scale the box to surround all your game area

10. Create and assign to ‘Boundary’ DestroyByBoundary.js

#pragma strict

// Destroy Game Objects START
function OnTriggerExit(other : Collider)
{
    // Destroy all GameObjects WITH COLLIDER that run away THIS Collider
    // The GameObject WITHOUT COLLIDER will not be detroyed!!!
    Destroy(other.gameObject);
}
// Destroy Game Objects END

11. Hierarchy> ‘Boundary’> Inspector> Remove ‘Mesh Filter”Mesh Renderer’

By |Unity3D, Video Games Development|Commenti disabilitati su Unity – Spaceship Shooting Game – JS – Laser Bolt

Unity – Spaceship Shooting Game – JS – Spaceship

Unity – Spaceship Shooting Game – JS – Spaceship

1. Hierarchy> select the Space Ship GameObject> Inspector> ‘Add Component’> Scripts> JS Script

The code of ‘PlayerController.js’:

#pragma strict

class Boundary
{
    // Theese variables are public to make the code easy-reusable
    // You can setup theese variables from Inspector
    var xMin : float;
    var xMax : float;
    var zMin : float;
    var zMax : float;
}

// Theese variables are public to make the code easy-reusable
// You can setup theese variables from Inspector
var speed : float;
var tilt : float;
var boundary : Boundary;

function FixedUpdate () {
     // Get User Input START
     var moveHorizontal : float= Input.GetAxis ("Horizontal");
     var moveVertical : float= Input.GetAxis ("Vertical");
     // Get User Input END

     var movement : Vector3= new Vector3 (moveHorizontal, 0.0f, moveVertical);
    rigidbody.velocity = movement * speed;

    // Limitate movement inside the screen START
    rigidbody.position = new Vector3 
    (
        Mathf.Clamp (rigidbody.position.x, boundary.xMin, boundary.xMax), 
        0.0f, 
        Mathf.Clamp (rigidbody.position.z, boundary.zMin, boundary.zMax)
    );
     // Limitate movement inside the screen END

    // Tilt movement START
    rigidbody.rotation = Quaternion.Euler (0.0f, 0.0f, rigidbody.velocity.x * -tilt);
    // Tilt movement END
}

2. Hierarchy> select the Space Ship GameObject> Inspector> ‘PlayerController.js’

– Speed
– Tilt

Boundary
– XMin: to get this value you can go to ‘Game’ view, select ‘Space Ship’ GameObject> Inspector> Transform> change X Position

– XMax: to get this value you can go to ‘Game’ view, select ‘Space Ship’ GameObject> Inspector> Transform> change X Position

– ZMin: to get this value you can go to ‘Game’ view, select ‘Space Ship’ GameObject> Inspector> Transform> change Z Position

– ZMax: to get this value you can go to ‘Game’ view, select ‘Space Ship’ GameObject> Inspector> Transform> change Z Position

By |Unity3D, Video Games Development|Commenti disabilitati su Unity – Spaceship Shooting Game – JS – Spaceship

UNITY – JS Script – OnTrigger

UNITY – JS Script – OnTrigger

1. Create a Sphere that falls and bource over a Box (You have to use Physics 3D engine)

2. Select the Box> Inspector> Box Collider> check ‘Is Trigger’, now the Box does not create collision, instead the Ball pass through it and this can be detected via code.

3. Attach to the Box the script


#pragma strict

function Start () {

}

function OnTriggerEnter (other : Collider) {
		print("Trigger Enter");
}

function OnTriggerStay (other : Collider) {
		print("Trigger Stay");
}

function OnTriggerExit (other : Collider) {
		print("Trigger Exit");
}

function Update () {


}

Unity has 3 OnCollision events:

1. OnTriggerEnter

TRUE at first frame of the collision
VERO al primo frame della collisione

2. OnTriggerStay

TRUE for some frames, until the colliders are still in contact
VERO per diversi frames, finchè i colliders sono in contatto

3. OnTriggerExit

TRUE the first frame when the colliders are no longer in contact
VERO al primo frame che perdono il contatto

NOTICE: put – function OnCollision – OUTSIDE Start() or Update()

By |Unity3D|Commenti disabilitati su UNITY – JS Script – OnTrigger