programming

Unity – Load a JPG local resource or www and apply to Texture or to UI Image

Hi Nice people!
Today I’ll talk about load a JPG image from an external source and use it in your games or apps, so let’s start!
First we have to stop watching image with eyes… I mean… now we’ll watch our full of color world as Neo of Matrix, we’ll see a sequence of bytes dropping everywhere :)

If you convert an image to byte array you will get something like that:

0x89,0x50,0x4E,0x47,0x0D,0x0A,0x1A,0x0A,0x00,0x00,0x00,0x0D,0x49,0x48,0x44,0x52,
0x00,0x00,0x00,0x40,0x00,0x00,0x00,0x40,0x08,0x00,0x00,0x00,0x00,0x8F,0x02,0x2E,
0x02,0x00,0x00,0x01,0x57,0x49,0x44,0x41,0x54,0x78,0x01,0xA5,0x57,0xD1,0xAD,0xC4,
0x30,0x08,0x83,0x81,0x32,0x4A,0x66,0xC9,0x36,0x99,0x85,0x45,0xBC,0x4E,0x74,0xBD,
0x8F,0x9E,0x5B,0xD4,0xE8,0xF1,0x6A,0x7F,0xDD,0x29,0xB2,0x55,0x0C,0x24,0x60,0xEB,
0x0D,0x30,0xE7,0xF9,0xF3,0x85,0x40,0x74,0x3F,0xF0,0x52,0x00,0xC3,0x0F,0xBC,0x14,

… etc …

This is the way used by Unity to see the images O.O

Let’s go on with practice, theory is boring :p

Load local JPG and apply to GameObject-Material-MainTexture

1. Create a Scene with a Cube and attach the script below:

2. c# script


using UnityEngine;
using System.Collections;
using System.IO; // namespace to use File.ReadAllBytes

public class LoadLocalTexture : MonoBehaviour {

	string filePath;        // it is as "D:/Unity/Photo-Voodoo/FotoTest/img1.jpg"

	public byte[] fileData; // load data inside a byte array 0x89,0x50,0x4E,0x47,0x0D...

	public void Start() {

		 filePath = "D:/MyFolder/img1.jpg";                   // the path of the image
		 fileData = File.ReadAllBytes(filePath);              // 1.read the bytes array
		 Texture2D tex = new Texture2D(2, 2);                 // 2.create a texture named tex
		 tex.LoadImage(fileData);                             // 3.load inside tx the bytes and use the correct image size
		 GetComponent<Renderer>().material.mainTexture = tex; // 4.apply tex to material.mainTexture 
	}// END Start
	
	void Update () {
	
	}// END Update()
}// END Mono


Load local JPG and apply to UI Image

1. Create a Scene with a UI Image and attach the script below:

2. c# script


using UnityEngine;
using System.Collections;
using UnityEngine.UI; // namespace to use UI
using System.IO; // namespace to use File.ReadAllBytes

public class LoadLocalTextureToImageUI : MonoBehaviour {

	string filePath;        // it is as "D:/Unity/Photo-Voodoo/FotoTest/img1.jpg"
	public byte[] fileData; // load data inside a byte array 0x89,0x50,0x4E,0x47,0x0D...

	public Image imageToDisplay; // Assign in Inspector the UI Image

	// Use this for initialization
	void Start () {

		filePath = "D:/MyFolder/img1.jpg";                   // the path of the image
		fileData = File.ReadAllBytes(filePath);              // 1.read the bytes array
		Texture2D tex = new Texture2D(2, 2);                 // 2.create a texture named tex
		tex.LoadImage(fileData);                             // 3.load inside tx the bytes and use the correct image size 
		Rect rec = new Rect(0, 0, tex.width, tex.height);    // 4.create a rect using the textute dimensions
		Sprite spriteToUse = Sprite.Create(tex,rec,new Vector2(0.5f,0.5f),100); //5. convert the texture in sprite
		imageToDisplay.sprite = spriteToUse;                 //6.load the sprite used by UI Image
	}// END Start()
	
	// Update is called once per frame
	void Update () {
	
	}// END Update()
}// END Mono

3. Assign in Inspector the UI Image to imageToDisplay variable

Load www JPG and apply to UI Image

1. Create a Scene with a Cube and attach the script below:

2. c# script


using UnityEngine;
using System.Collections;
using UnityEngine.UI; // namespace to use UI

public class LoadwwwTextureToImageUI : MonoBehaviour {

	public Image imageToDisplay; // Assign in Inspector the UI Image
	public string addressWeb = "http://www.lucedigitale.com/img1.jpg";

	// Use this for initialization
	void Start () {

		StartCoroutine(isDownloading(addressWeb)); 

	}// END Start()
		

	IEnumerator isDownloading(string url){
		yield return new WaitForSeconds(1); // wait for one sec, without it you will have a compiiler error
		
		
		var www = new WWW(url); // 1.start a download of the given URL           
		yield return www;       // 2.wait until the download is done
                                        // 3.create a texture in DXT1 format
		Texture2D texture = new Texture2D(www.texture.width, www.texture.height, TextureFormat.DXT1, false);
		                        
		www.LoadImageIntoTexture(texture); //4.load data into a texture
		Rect rec = new Rect(0, 0, texture.width, texture.height); //5.create a rect using texture dimensions
		Sprite spriteToUse = Sprite.Create(texture,rec,new Vector2(0.5f,0.5f),100); // 6.convert the texture to sprite
		imageToDisplay.sprite = spriteToUse; //7.change the sprite of UI Image

		www.Dispose(); //8.drop the web connection NOTE: Unity drop automatically the connection at the end of the download, but we put it as a precaution

		www = null;

	}// END IEnumerator

	void Update () {
	
	}// END Update()

}// END Mono

3. Assign in Inspector the UI Image to imageToDisplay variable

I hope this article has been helpful, greetings :)

Reference: https://docs.unity3d.com/ScriptReference/Texture2D.LoadImage.html
Reference: http://answers.unity3d.com/questions/1122905/how-do-you-download-image-to-uiimage.html

By |CSharp, Unity3D, Video Games Development|Commenti disabilitati su Unity – Load a JPG local resource or www and apply to Texture or to UI Image

Google Cardboard and Gear VR Basic Scene Setup

I think it is the right moment to talk abour VR in games and in multimedia entertainment.

WHAT IS VIRTUAL REALITY?

The word ‘virtual reality’ has been used and abused for many years in the comics and in science fiction films.

In the 70s science fiction movies VR was imagined as a computer-simulated reality that replicates an environment, real or imagined, and simulates a user’s physical presence and environment to allow for user interaction.

In the ‘real life’ Atari founded a research lab for virtual reality in 1982, but the lab was closed after two years due to Atari Shock (North America video game crash of 1983).

In 1991, Sega announced the Sega VR headset for arcade games and the Mega Drive console. It used LCD screens in the visor, stereo headphones, and inertial sensors that allowed the system to track and react to the movements of the user’s head.

On 2014, Facebook purchased a company that makes virtual reality headsets, Oculus VR, for $2 billion. Sony announces Project Morpheus (its code name for PlayStation VR), a virtual reality headset for the PlayStation 4. Google announces Cardboard, a do-it-yourself stereoscopic viewer for smartphones.

On 2015, HTC partnered with Valve Corporation announced their virtual reality headset HTC Vive and controllers, along with their tracking technology called Lighthouse.

Now the technology to make VR is reality, and it is accessible to all, now it is up to software developers to create killer applications to exploit it properly.

HOW IT WORKS?

Stereoscopy is the keyword. Stereoscopy is a technique for creating or enhancing the illusion of depth in an image by means of stereopsis for binocular vision.
Most 3D displays and gears use this stereoscopic method to convey images. It was first invented by Sir Charles Wheatstone in 1838, then… not science fiction but old story.

SOFTWARE SETUP

1. Download Java SE Development Kit 8 http://www.oracle.com/technetwork/java/javase/downloads/jdk8-downloads-2133151.html
Install it.

2. Download Android Studio https://developers.google.com/vr/unity/get-started-android
Install using the “SDK Tools Only” option.
On some Windows systems, the launcher script does not find where the JDK is installed. If you encounter this problem, you need to set an environment variable indicating the correct location.
Select Start menu > Computer > System Properties > Advanced System Properties. Then open Advanced tab > Environment Variables and add a new system variable JAVA_HOME that points to your JDK folder, for example C:\Program Files\Java\jdk1.8.0_77.

3. Download the Google VR SDK for Unity here: https://developers.google.com/vr/unity/

4. Open Unity (working with the Google VR SDK for Unity requires Unity 5.2.1 or later)
Assets> Import Package> ‘GoogleVRForUnity.unitypackage’, uncheck Plugins/iOS and ‘Import’.
Under Project window we will see Assets/GogleVR and Assets/Plugin

NOTICE: if the Unity console write about a script error, ignore it and Switch Platform to Android

5. Unity> Build Settings> Android and Texture Compression ETC2 (GLES 3.0)

UNITY CAMERA BASIC SETUP

1. Create a New Scene

2. Create a Plane and a Cube

3. Project> Assets> GoogleVR> Prefabs> GvrMain DRAG AND DROP in Hierarchy

4. Hierarchy> GvrMain > Head> Main Camera> Inspector> Add Component> Physics Raycaster (NOT THE Physics 2D Raycaster!!!)
The Raycaster raycasts against 3D objects in the scene. This allows messages to be sent to 3D physics objects that implement event interfaces.

5. Delete the old ‘Main Camera’

6. Project> Assets> GoogleVR> Prefabs> UI> GvrReticle, DRAG AND DROP in Hiearchy over Main Camera, here we are:
GvrMain
– Head
– – Main Camera
– – – Main Camera Left
– – – Main Camera Right
– – – CardboardRetiche

7. Press Play and rotate the camera using ALT + move the mouse without clicking.

UNITY INPUT SETUP

1. RMB on a empty area in Hierarchy> UI> add an ‘Event System’

2. Event System> Inspector> Add Component> GazeInputModule.cs, gear icon> ‘Move Up’ the component, the correct order is:

Transform
EventSystem (Script)
GazeInputModule (Script)
Standalone InputModule (Script)

3. Cube> Inspector> assign a Green material

4. Cube> Inspector> Add Component> EventTrigger (Script)> ‘Add New Event Type’> Pointer Enter> +> in the Empty Slot DRAG Cube, No Function> MeshRenderer> Material> DRAG a Red material

5. Cube> Inspector> Add Component> EventTrigger (Script)> ‘Add New Event Type’> Pointer Exit> +> in the Empty Slot DRAG Cube, No Function> MeshRenderer> Material> DRAG a Green material

6. Play

– pointer Enter material changes to Red
– pointer Exit material changes to Green

The interactions detection system flow is:

a) main Camera/Physics Raycaster + CardboardReticle send rays
b) rays casts Cube/Box Collider
c) Cube/Event Trigger sends data to Hierarchy/EventSystem
d) Hierarchy/EventSystem + Gaze Input Module manages data

If it does not work check the ‘Physics Raycaster (Script)’ attached to the Main Camera or the Box Collider of the Cube.

CARDBOARD / GEARVR BUILDING SETUP

1.
GearVR:
– Player Settings> Virtual Reality support enabled -> this split the camera and track position/rotation for GearVR only
– GvrMain> GvrViewer (Script)> VR Mode disabled
– GvrMain> Head> GvrHead (Script)> Track position disabled
– GvrMain> Head> GvrHead (Script)> Track rotation disabled

Card Board:
– Player Settings> Virtual Reality support disabled
– GvrMain> GvrViewer (Script)> VR Mode enabled -> this split the camera for Card Board only
– GvrMain> Head> GvrHead (Script)> Track position enabled -> this track position for Card Board only
– GvrMain> Head> GvrHead (Script)> Track rotation enabled -> this track rotation for Card Board only

2.
Build Settings> Player settings
– Company Name: MyCompany
– Product Name: CardBoardTest
– Default orientation: Landscape Left
– Multithreaded Rendering: on
– Bundle Identifier: com.mycompany.cardboardtest
– Minimum API Level: Android 4.1 (API Level 16)
– Device Filter: ARMv7
– Android TV Compatibility: off

3. Add the corrent scene to build

4. Build and Play!

5. Assets> Plugins> Android> create a folder ‘assets’, copy here your oculus signature file, generate it using https://developer.oculus.com/osig/

References:
Wikipedia – https://en.wikipedia.org/wiki/Stereoscopy
Dev Android – https://developer.android.com/studio/index.html
NurFACEGAMES – https://www.youtube.com/watch?v=eLCj6_gtLc4

By |CSharp, Unity3D, Video Games Development|Commenti disabilitati su Google Cardboard and Gear VR Basic Scene Setup

PHP Development – Easy PHP – NetBeans IDE for noobs

What is and IDE?

To develop HTML and CSS you can use an advance notepad as NotePad++ (http://notepad-plus-plus.org/).
A tool like that is very useful for:
– Syntax Highlighting and Syntax Folding
– Auto-completion: Word completion, Function completion and Function parameters hint
– Multi-View

To edit simple PHP code you can use NotePad++ but if you want develop an application with variables and classes you will need an IDE environment. An integrated development environment (IDE) or interactive development environment is a software application that provides comprehensive facilities to computer programmers for software development.
An IDE normally consists of:
– Syntax Highlighting and Syntax Folding
– Auto-completion: Word completion, Function completion and Function parameters hint
– Multi-View
– Build Automation Tool
– Debugger
– Ready to use code for graphic elements as windows, slides, buttons.
– Project Support to organize files better

Debugger help you to find evil bugs in less time.

Today we will try NetBeans IDE (https://netbeans.org/).
NetBeans IDE is free and by Oracle.

What is a WAMP?

A WAMP (Windows web development environment) allows you to create web applications with Apache, PHP and a MySQL database without installing them in your system. It is a like a magic standalone box :)

I like to use EasyPHP(http://www.easyphp.org/).

Install and Run EasyPHP

1. Go to http://www.easyphp.org/ download ‘E Development Server’ and install

2. Go to your installation folder, usually Programmi(x86)> EasyPHP> data> localweb> www> create the folder ‘test-net-beans’

3. If you have Skype running, drop it because it uses the same port of EasyPHP

4. Run EasyPHP

5. Barra di Windows> icone nascoste> RMB over EasyPHP> Administrator to see versions of Apache PHP and MYSQL

6. Barra di Windows> icone nascoste> RMB over EasyPHP> Local Web> www, to see the root folder of your website

Install and Run NetBean IDE

1. Download the package here http://www.oracle.com/technetwork/java/javase/downloads/jdk-netbeans-jsp-142931.html
This package includes NetBeans 8.0.2 + JDK, one installation, two packages!
Lanch the .exe and install

2. Open NetBeans IDE> MAIN TOP MENU> Tools> Plugins> ‘Available Plugins’ tab> check PHP> ‘Install’ button, then restat IDE

New Project – Hello World!

0. Run NetBeans IDE

1. MAIN TOP MENU> File> New project> PHP Application

2.
Project Name: TestNetBeans
Sources Folder: usually Programmi(x86)> EasyPHP> data> localweb> www> test-net-beans
PHP Version: the same setup in barra di Windows> Icone nascoste> RMB Easy PHP> Administration

3.
Run As: Local Web Site
Project URL: http://localhost/www/test-netbeans/

4. PHP Frameworks: leave blank

NOTICE: inside Programmi(x86)> EasyPHP> data> localweb> www> create the folder ‘test-net-beans’ now there is the folder /nbproject

5. NetBeans> MAIN TOP MENU> File> New File> PHP> PHP File (empty php file)

6.
File Name: index
Folder: Browse the root folder or wherever you want, ‘Finish’, good! We have our first index.php! Congrats!

7. Write inside index.php:


<?php
/* 
 * My first index file
 */
echo "Hello World!";
?>

8. MAIN TOOLBAR> Play!

PHP Application with Existing Sources

0. Run NetBeans IDE

1. MAIN TOP MENU> File> New project> PHP Application with Existing Sources

2.
Project Name: TestNetBeans
Sources Folder: usually Programmi(x86)> EasyPHP> data> localweb> www> my-old-project
Project Name: my-old-project
PHP Version: the same of EasyPHP

3.
Run As: Local Web Site
Project URL: http://127.0.0.1/www/my-old-project/
NOTE: you can modify later at File> Project Properties> Run Configuration> Project URL
Index Folder: index.php or other

Debug

1. NetBeans> MAIN TOP TOOLBAR> Debug Project, it will open a page like this: ‘http://127.0.0.1/www/my-website-folder/index.php?XDEBUG_SESSION_START=netbeans-xdebug

2. MAIN TOOL BAR> ‘Step Into'(F7) to debug step by step

Resume

The combination of tools is simple:

1. Easy PHP acts like a webserver, run Apache, PHP and MySQL in a sandbox and hosts the web site inder /www/mysite folder
2. NetBeans create a project file inside /www/mysite/nbproject and manages/edits .php files inside /www/mysite folder

NeBeans IDE edit -> | /www folder of EasyPHP WAMP |

By |PHP, Web Design|Commenti disabilitati su PHP Development – Easy PHP – NetBeans IDE for noobs

Unity3D – Tutorials – UI – Input Field – JS

Unity3D – Tutorials – UI – Input Field – JS

The new UI system give us a new Input Field, in this tutorials we are going to create a responsive ‘Input Field’ in the middle of the screen, get the user input and render it over a label.

Create a scene with:

– Main Camera

– Canvas
-> InputField
->> Placeholder
->> Text (the text of InputField)
-> Text (a label)

– EventSystem

– GameControl (Empty)

Hierarchy> Canvas> Inspector> Canvas Scaler (Script):
– Reference Resolution: X=800 Y=600
– Screen Marìtch Mode: Match Width Or Height

Hierarchy> InputField> Inspector
> Rect Transform
– Pos X=0 Y=0 Z=0
– Width= 200 Height=30
> Input Field (Script)
– Character Limit = 10 (max 10 characters allowed)

Hierarchy> InputField> Placeholder> Inspector
> Text (Script)
– Text= ‘Enter your name…, max 10 characters’

Hierchy> Text (a label)> Inspector
> Rect Transform>
– Pos X=0 Y=0 Z=0
– Width= 100 Height=100

> Text (Script)
– Text= ‘Your name here’

Now we will see in the middle of the screen:

Your name here -> (label)
|Enter your name…, max 10 characters | -> (Input Field)

Attach to GameController gameobject GameControllerScript.js:


#pragma strict
 
var MyInputField : UI.InputField; // ASSIGN IN INSPECTOR the InputField 
var TextGetInputField : UI.Text; // ASSIGN IN INSPECTOR the text of InputField
var TextLabel: UI.Text; // ASSIGN IN INSPECTOR the text of the label
 
function Awake () {
}// END Awake()
 
function Start () {
        // Focus on InputField if doesn't make sense to force the user to click on it.
	MyInputField.ActivateInputField();
	MyInputField.Select();
}// END Start()
 
function Update () {
	TextLabel.text = 'Your name is: ' + TextGetInputField.text;
}// END Update()

Hierarchy> Canvas/InputField> DRAG AND DROP over var MyInputField
Hierarchy> Canvas/InputField/Text> DRAG AND DROP over var TextGetInputField
Hierarchy> Canvas/Text> DRAG AND DROP over var TextLabel

Play and enjoy!

I like group all UI game objects in a single script, getting they from Inspector, in my opinion it is the easy way to manage a lot of text.

Reference: http://docs.unity3d.com/460/Documentation/ScriptReference/UI.InputField.html

By |Unity3D, Video Games Development|Commenti disabilitati su Unity3D – Tutorials – UI – Input Field – JS

Unity3D – Tutorials – UI – Scroll Rect – Image

Unity3D – Tutorials – UI – Scroll Rect – Image

Inside a Scrool Rect you can scroll an image greater than the Scroll Rect Area.

Scrool Rect – No ScroolBars

0. MAIN TOP MENU> GameObject> UI> Canvas

1. MAIN TOP MENU> GameObject> UI> Image

2. MAIN TOP MENU> GameObject> Empty Object, rename it ScrollRectObj

3. Hierarchy> select ScrollRectObj> Inspector> ‘Add Component’
> Scroll Rect (Transform component will be authomatic removed)
> Image
> Mask

4. Parent as show below:

– Canvas
-> ScrollRectObj (child of Canvas)
->> Image (child of ScrollRectObj)

5. Setup size and position:

– Inspector> ScrollRectObj: Width= 100 Height= 100 Pos XYZ= 0,0,0

– Inspector> Image: Width= 200 Height= 200 Pos XYZ= 200,0,0

The Image is greater than ScrollRectObj and in a different position

6. Setup ScrollRectObj

– Inspector> ScrollRectObj> Scroll Rect (Script)> Content, DRAG AND DROP from ‘Hierachy> Image’ here

Play, Image will be moved inside ScrollRectObj, DRAG the image to move it

WARNING: the best practice is put the Image already inside the Scrool Rect, then please modify:
Inspector> Image: Width= 200 Height= 200 Pos XYZ= 0,0,0

Scrool Rect – Yes ScroolBars

1. Hierarchy> RMB over Canvas> UI> Scrollbar

– Canvas
-> ScrollRectObj (child of Canvas)
->> Image (child of ScrollRectObj)
-> Scrollbar (MUST BE CHILD OF CANVAS)

2. Hierarchy> select Scrollbar DRAG AND DROP Inspector> ScrollRectObj> Scroll Rect (Script)> Horizontal Scrollbar

3. Play and enjoy!

By |Unity3D, Video Games Development|Commenti disabilitati su Unity3D – Tutorials – UI – Scroll Rect – Image