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

Unity 3D – Animation calls Functions – Animation Events – JavaScript

Unity 3D – Animation calls Functions – Animation Events – JavaScript

Animation Events, which allow you to call functions in the object’s script at specified points in the timeline.

Official docs: http://docs.unity3d.com/Manual/animeditor-AnimationEvents.html

1. Create a Cube

2. Attach Cube.js:

// This JavaScript function can be called by an Animation Event
function PrintFloat (theValue : float) {
    Debug.Log ("PrintFloat is called with a value of " + theValue);
}

3. Select the Cube GameObject, MAIN TOP MENU> Window> Animation> Animation Toolbar>
> Add Keyframe, create your animation
> Add Event, Select a function, setup a value

4. Play

By |Unity3D, Video Games Development|Commenti disabilitati su Unity 3D – Animation calls Functions – Animation Events – JavaScript

Unity3D – Texture Mover – Javascript

Unity3D – Texture Mover – Javascript

How to move texture via code.

Create a Plane with
– Material with a _MainTex (if you use a diffuse material it is the main color texture)
– TextureMover.js

Simple code:


#pragma strict

    // Scroll main texture based on time
	var scrollSpeed : float; // Assign in Inspector, start try 0.5

function Start () {
    // setup Main Texture (scaleX,scaleY) 
    // x = 0.5 perchè la texture che uso è il doppio in larghezza della dimensione del piano
    // il piano è 16:9, ta texture 32:9 per avere un landscape più ampio
	renderer.material.SetTextureScale ("_MainTex", Vector2(0.5,1));
}// END Start()

function Update () {
        var offset : float = Time.time * scrollSpeed;
		renderer.material.SetTextureOffset ("_MainTex", Vector2(offset,0));
}// END Update()

Play to see the final result

Pro code:


#pragma strict

    var isVertical : boolean = false; // check in Inspector if you need a vertical scrool 
    
    var invertDirection : boolean = false; // check in Inspector if you need change scrool direction
    
    // Scroll main texture based on time
	var scrollSpeed : float; // Assign in Inspector, start try 0.5
	
	var scaleX : float; // X scale of the texture
	var scaleY : float; // X scale of the texture

function Start () {

    // setup Main Texture (scaleX,scaleY) START ###############################################
    // ad esempio scaleX = 0.5 se la texture che uso è il doppio in larghezza della dimensione del piano
    // il piano è 16:9, la texture 32:9 
	renderer.material.SetTextureScale ("_MainTex", Vector2(scaleX,scaleY));
	// setup Main Texture (scaleX,scaleY) END #################################################
	
}// END Start()

function Update () {

        MoveTexture(); // devo richiamarla da update perchè si deve aggiornare ad ogni frame
        
}// END Update()

function MoveTexture(){

        var offset : float; // lo spostamento della texture...
        
        // left->right or right->left or up->down or down->up ----------------------------------------------
	    if (invertDirection){ // positivo
	    offset = Time.time * -scrollSpeed; 
	    } 
	    
	     if (!invertDirection){ // negativo
	    offset = Time.time * scrollSpeed; 
	    }
        // vertical or horizontal  -------------------------------------------------------------------------
	    if (isVertical) { // in verticale 
	        renderer.material.mainTextureOffset = Vector2 (0, offset);  
	    }else{  // in orizzontale
	        renderer.material.mainTextureOffset = Vector2 (offset, 0);  
	    } 
  
}// END MoveTexture()


Setup in Inspector the value of variables

Play, you can change values on the fly into Inspector!

By |Unity3D, Video Games Development|Commenti disabilitati su Unity3D – Texture Mover – Javascript