videogames development

Unity3D – What is Object Pooling

Unity3D – Object Pooling

What is a pool?
In computer science, a pool (piscina) is a set of initialised resources that are kept ready to use, rather than allocated and destroyed on demand.
A client of the pool will request an object from the pool and perform operations on the returned object. When the client has finished with an object (or resource), it returns it to the pool rather than destroying it.

What is object pooling?
In games you need to manage a lot gameobjects at one time (bullets, enemies etc…), and istantiate and destroy every object can slow down your game performance.
To improve performance and save CPU time the best way is create a pool of gameobjects and request gameobjects from the pool.

For example you can have an gameObject off screen named “enemies” which holds all the enemies, and a master script to manage it:

enemies (Empty Game Object) -> master script ‘Enemy.js’
|
|—-enemy
|
|—-enemy
|
|—-enemy

Another example is reuse bullets:

Slower performance:
1. Awake(), do nothing
2. Update()
a- Instantiate bullet in its start position
b- Move along the way
c- Move bullet in its final position
d- Destroy bullet

Object Pooling. best performance:
1. Awake(), create a pool off screen
2. Update ()
a- Get gameobject bullet from the pool
b- SetActive -> true, Move bullet in its start position
c- Move along the way
d- Move bullet in its final position
e- SetActive -> false
f- Reuse from point b- and so on…

In terms of performance for real scenarios, if you use only 10-50 gameobjects at one time the benefits of object pooling are irrelevant.

In Unity3D you will need object pooling when you have thousands of gameObjects at one time or if you develop for slower mobile devices.

References:

http://answers.unity3d.com/questions/321762/how-to-assign-variable-to-a-prefabs-child.html

http://unity3d.com/learn/tutorials/modules/beginner/live-training-archive/object-pooling

By |Unity3D, Video Games Development|Commenti disabilitati su Unity3D – What is Object Pooling

Unity3D – Game Engine – Get Material Name

Unity3D – Game Engine – Get Material Name

Get the material of THIS gameobject.
IMPORTANT: material is not a Component but a class of renderer Component, the correct statement is:

...
// GameObject.Component.Class.Property
this.renderer.material.name
...

Create a Cube, assign a material named ‘material0’, assign the script:


#pragma strict

function Start () {

}

function OnMouseDown ()
{
        // When you click over the object play audio
        audio.Play();
        
        // Check material
        // NB: il materiale non è un componente ma una classe di renderer!!!!
        var myMaterial = renderer.material;
        Debug.Log(myMaterial); // -> Risulta: material0 (Instance)
        
    if (this.renderer.material.name == "material0 (Instance)") {
        Debug.Log("material0 found!");
    } else {
        Debug.Log("material0 not found!");
    }
}

function Update () {

}

By |Unity3D, Video Games Development|Commenti disabilitati su Unity3D – Game Engine – Get Material Name

Unity3D Game Engine – Materials Array

Unity3D Game Engine – Materials Array

Array of Materials

Create a scene with:

– Main Camera

– 3 Materials blue-green-red

– Cube, assign the script SwitchMaterials.js:


#pragma strict
 
var materials : Material[];
var materials_counter : int = 0; // 1. Setup this in Inspector! It setup the array lenght!
                                 // 2. DRAG AND DROP materials inside slots
function Update() 
{
    if(Input.GetKeyDown("f")) // press f key to switch materials
    {
        renderer.material = materials[GetNextMaterialIndex()]; // richiama l'indice del materiale da visualizzare
                                                               // risulta -> render.material = materials[0]
    }
}
 
function GetNextMaterialIndex() : int
{
    materials_counter++; // incrementa di 1 l'indice
    if (materials_counter==materials.Length)
    {
        materials_counter = 0; // se l'indice è già uguale alla lunghezza massima riporta il valore a 0
    }
    return materials_counter; // ritorna l'indice dell'array
}

Cube> Inspector> SwitchMaterials.js>
1. Dare un valore a Materials Size (è la lunghezza dell’indice)
2. DRAG AND DROP i materiali sugli slot Element 0-1-2 etc…

Play> press f to switch materials.

By |Unity3D, Video Games Development|Commenti disabilitati su Unity3D Game Engine – Materials Array

Unity3D – Game Engine – Artificial Intelligence

Unity3D – Game Engine – Artificial Intelligence

What is AI?

Artificial Intelligence (AI) is essentially the subject of making computers able to think and decide like living organisms to perform specific operations. AI in videogame is the brain of NPC (Non Player Characters), the computer-driven characters.

AI setup

Our NPC opponents can be very stupid like a zombie or super intelligence as the chess game champion Kasparow but the important thing it is our game have to be funny! The NPC can not be invicible or too easy to win. Finding the right challenge level is the key to make a game fun to play.
There are a lot of techniques, so let’s go on!

Finite State Machines

It is the the simplest AI model.
A state machine basically consists of a finite number of states that are connected in a graph by the transitions between them.

NPC character -> It follows some rules -> It changes state

NPC character can only be in exactly one state at any given time.

Random and Probability

In videogames, randomness and probabilities are applied in the decision making process of AI calculations.

Stupid NPC
-> good way (30%) -> it is easy to beat it!
-> bad way (70%)

Genius NPC
-> good way (90%) -> run fast and escape!
-> bad way (10%)

Sensor System

Our NPCs need eyes and ears to know about enemies and world they are interacting with.
The basic informations the NPCs need could vary a lot depending on the type of the game, for example:

NPC in a RTS (Real Time Startegy) game:
– Position of the player
– Buildings and objects nearby
– Player’s health and its own health
– Location of resources on the map

NPC zombie:
– Position of the player (to eat him…) :)

Pooling

One method to collect the informations of the world is polling.
NPCs -> Pooling (if/else) -> Reaction

We can simply do if/else or switch checks in the FixedUpdate() method of our AI character.

The messaging system

NPC AI does decision making in response to the events in the world.
The messaging system provides a central checking system.

Event -> NPCs (listeners) -> Pooling -> Reaction

Flocking, swarming, and herding

Think about group of birds flocking in the sky. We can define simple rules for each bird to create the whole group behaviour.

There are 3 simple rules:
– Separation: minimum distance between neighbors
– Alignement: direction based on direction of the neighbors
– Cohesion : minimum distance with the group’s center of mass

Path following and steering

Think about a racing game, the AI opponents need to navigate on the road.

A* (star) Pathfinding

The AI units need to find a path to reach the goal without colliding with the obstacles or colliding with others NPC.
A* (pronounced “A star”) is a pathfinding algorithm widely used in games, because of its performance and accuracy.

A Navigation Mesh

A navigation mesh it is a poly mesh that uses polygons to represent the areas in the map that an AI entity can travel. It is the ‘road’ of our NPCs players. An NPC will knows more informations about world than a waypoint system as A* Pathfinding system. The AI character will knows the safe areas, if there is mud, grass, ice, water and so on…
Unity3D Pro has a built-in navigation mesh generator.

Behavior Trees

With a behavior tree you can represet the logic of an AI character.

NPC Action
|1.-> |Is Player faraway?
|Patrol (Ispeziona)
|2.-> |Do I see the Player?
|Chase (Raggiungi)
|3.-> |Is Player near enought to attack?
|Attack (Attacca)

Try to think as your NPC:
1. The Player is faraway -> Patrol |2. I see the Player -> Chase |3. I am near enough -> Attack
The NPC can not reach point 3. if do not reach point 2. first.
Point 3. it is the child behaviour of point 2.

Locomotor System

Locomotor system manages different NPC’s walk cycles to walk on plane, run, climb a ladder, attack an enemy etc…
Unity3D pro has a built-in locomotion system: Mecanim

By |Unity3D, Video Games Development|Commenti disabilitati su Unity3D – Game Engine – Artificial Intelligence

Unity3D – 2D Games – Pixel Perfect 2D Game

Unity3D – 2D Games – Pixel Perfect 2D Game

Un rendering ‘pixel perfect’ lo abbiamo quando la risoluzione in uscita di un gioco e la dimensione di uno sprite corrispondono in pixel.
Immaginiamo di avere un progetto in WebPlayer di 800×600 pixel, di importare uno sprite di 400×600, se lo sprite ricopre metà del display allora è un rendering ‘pixel perfect’

Unity3D isn’t designed for pixel perfect rendering, this cause artifacts, and pixel blurring.

Perfect user interface buttons

To remove artifacts you have to do:

1. Import Texture 512×512
Migliora l’interpolazione di Unity3D

2. Texture> Inspector>
– Filter Mode: Bilinear
Pulisce l’interno della texture

Format TrueColor
Elimina la compressione del colore per far scomparire l’effetto squadrettato tipo JPG

3. Material> Shader Transparent/Cutout/Soft Edge Unlit
Rende più morbido il bordo della maschera alfa

Perfect spritesheet

To remove artifacts you have to do:

– You will likely need a texture with “power of 2” dimensions, e.g. 256 – 512 – 1024px.
– Texture filter mode should be “point”
– Turn off texture compression
– If you are using Unity ‘Sprite’ texture type, take care with your sprite pixels to units setting
– Take care with your orthographic camera scale relative to your screen dimensions

If you want the orthographic camera to match your screen resolution, then set the camera Size to be half of your screen height. So, in this case, if your window is 600 pixels, set your camera Size value to be 300.

For italian people:

– Importare texture multiple di 2px ‘128 – 256 – 512 – 1024px’
-> per evitare l’interpolazione applicata da Unity automaticamente per portarle a dimensioni multiple di 2

– Project> my-spritesheet> Inspector> Filter Mode> Point
-> RENDE I PIXEL PIU’ DEFINITI perchè toglie i filtri bilineari e trilineari

– Project> my-spritesheet> Inspector> Default> Format> Truecolor
-> elimina la compressione dei colori della texture

– Project> my-spritesheet> Inspector> Pixels to Units
-> definisce la corrispondenza tra il numero di pixel e le unità Unity3D ad esempio: 100px per 1 unità Unity3D
Ottimizzare questo parametro per gestire la dimensione degli sprite a video.

– Main Camera> Projection> Orthographic
-> per utilizzare una camera senza deformazioni prospettiche.

– Main Camera> Size
-> definisce quante unità Unity3D in altezza sarà la vista della camera, ad esempio: 15 significa che la camera in altezza inquadrerà lo spazio di 15 unità.
Ottimizzare questo parametro per gestire la dimensione degli sprite a video.

– MAIN TOP MENU> Edit> Project Settings> Quality> Texture Quality> Full Res

Se si vuole che la camera ortografica corrisponda alla risoluzione a video, settare il camera ‘Size’ alla metà dell’altezza della risoluzione a video. Ad esempio se l’altezza del video è 600px il camera ‘Size’ sarà 300.

By |Unity3D, Video Games Development|Commenti disabilitati su Unity3D – 2D Games – Pixel Perfect 2D Game