videogames development

Unity 3D Game Engine – Get Screenshot – Android

Unity 3D Game Engine – Get Screenshot – Android

How to get a in-game Screenshot with Unity 3D – UNTESTED

IMPORTANT!!!

Unity> MAIN TOP MENU> File> Build Settings> Player Settings…> Other Settings> Configuration> Write Access> External (SD Card), this setup will create inside Android Device using Windows 7 -> Phone/Android/data/com.Company.LuceDigitale

It this equal the write inside AndroidManifest.xml ->

Method 1

Application.CaptureScreenshot

NOTICE: CaptureScreenshot is asynchronous. This is because capturing and saving the screen can take awhile.

Inside Hierarchy create a structure with:

1. Some Objects

2. Main Camera, attach the script ‘GetScreenShot.js’

GetScreenShot.js


#pragma strict

// For Android Devices ONLY
// Attach this script to Main Camera

// File> Build Settings> Player Settings...> Other Settings> Configuration> Write Access> External (SD Card),
// this setup will create inside Android Device using Windows 7 -> Phone/Android/data/com.Company.LuceDigitale
// It this equal the write inside AndroidManifest.xml ->  <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

var scoreTextX : GUIText;
var localize   : String;

function Start() {
}

function OnGUI()
{
  if (GUI.Button(Rect(10,10,200,50),"Capture Screenshot"))
  { 
    // debug data path
    localize = Application.persistentDataPath;
    scoreTextX.text = localize;
    // it writes:  /storage/sdcard0/Android/data/<bundle id>/files folder
    
    // We should only read the screen buffer after rendering is complete
    yield WaitForEndOfFrame();
    
    // Application.dataPath DOES NOT have write permission on Android, you need Application.persistentDataPath
    // static function CaptureScreenshot(filename: string, superSize: int = 0): void;
    Application.CaptureScreenshot("Screenshot.png");
    // the file will be saved on: /storage/sdcard0/Android/data/<bundle id>/files folder
  }
}

By |Unity3D, Video Games Development|Commenti disabilitati su Unity 3D Game Engine – Get Screenshot – Android

How to get GPS coordinates in Unity 3D

How to get GPS coordinates in Unity 3D

Inside Hierarchy create a scene with:

1. GUI Texture
2. Main Camera, attach the script ‘GetGpsCoord.js’

GetGpsCoord.js


#pragma strict

// Hierarchy DRAG E DROP over var GUI Text in Inspector
var scoreTextX : GUIText;
var localize   : String;

function Start () {
        // First, check if user has location service enabled
        if (!Input.location.isEnabledByUser)
            return;
        // Start service before querying location
        Input.location.Start ();
        // Wait until service initializes
        var maxWait : int = 20;
        while (Input.location.status
               == LocationServiceStatus.Initializing && maxWait > 0) {
            yield WaitForSeconds (1);
            maxWait--;
        }
        // Service didn't initialize in 20 seconds
        if (maxWait < 1) {
            print ("Timed out");
            return;
        }
        // Connection has failed
        if (Input.location.status == LocationServiceStatus.Failed) {
            print ("Unable to determine device location");
            return;
        }
        // Access granted and location value could be retrieved
        else {
        localize = Input.location.lastData.latitude + " " +
                   Input.location.lastData.longitude + " " +
                   Input.location.lastData.altitude + " " +
                   Input.location.lastData.horizontalAccuracy + " " +
                   Input.location.lastData.timestamp;
                                      
                   scoreTextX.text = "GPS coordinates "+localize;
        }
        // Stop service if there is no need to query location updates continuously
        Input.location.Stop ();
    }

Hierarchy> Main Camera> GetGpsCoord.js> DRAG AND DROP GUI Texture over var scoreTextX

The final result is:

45.04529 -> latitude
11.72339 -> longitude
0 -> altitude
2099 -> horizontalAccuracy
1396651772.795 -> timestamp

By |Unity3D, Video Games Development|Commenti disabilitati su How to get GPS coordinates in Unity 3D

Unity 3D Game Engine – be or not be kinematic

Unity 3D Game Engine – be or not be kinematic, this is the problem…

When we will create a pick up game object, do we need a kinematic or a non-kinematic object?

PickUp Object

1. Create a Cube (PickUp) as ‘Prefab’ to easy duplicate it, with:

SOLUZIONE 1: senza ‘Rigid Body’, lo considera un ‘Collider Statico’, come un muro, e quindi calcola e salva in cache la posizione una volta per tutte, questo ha senso per risparmiare calcoli in caso di un oggetto che non si muove. Se il nostro cubo ruota Unity salva in cache ogni volta la nuova posizione per ogni frame occupando risorse di sistema.
– Box Collider -> check ‘Is Trigger’ -> così non si effettuano calcoli fisici perchè il ‘Trigger’ rileva solo le collisioni senza causare reazioni fisiche

OPPURE

SOLUZIONE 2: applicando un ‘Rigid Body’, lo considera un Collider dinamico, e non salverà dati in cache, occupando meno risorse.
a. Rigid Body> Disabilitare ‘Use Gravity’ per non far cadere l’oggetto. L’oggetto risponde ancora alle sollecitazioni provenienti da altri Collider.
b. Rigid Body> Abilitare ‘Is Kinematic’ per non far calcolare a Unity le reazioni alle sollecitazioni provenienti da altri Collider e ottimizzare il consumo di CPU. Un oggetto ‘Is Kinematic’ può essere spostato utilizzando la funzione ‘Transform’. Questo setup è tipico delle piattaforme mobili di un videogioco ‘platform’.

By |Unity3D, Video Games Development|Commenti disabilitati su Unity 3D Game Engine – be or not be kinematic

Unity 3D Game Engine – Android – Accelerometer – RAW Data – Translate and Object

Unity 3D Game Engine – Android – Accelerometer – RAW Data – Translate and Object

Inside Hierarchy create:

– Main Camera
– GUI Text X
– GUI Text Y
– GUI Text Z
– Cube (Game Object), attach ‘AccelerometerTest.js’

AccelerometerTest.js


#pragma strict

// Hierarchy DRAG E DROP over var GUI Text in Inspector
var scoreTextX : GUIText;
var scoreTextY : GUIText;
var scoreTextZ : GUIText;

	function Update () {
		var dir : Vector3 = Vector3.zero; // Shorthand for writing Vector3(0, 0, 0)
		
		dir.x = Input.acceleration.x;
		dir.y = Input.acceleration.y;
		dir.z = Input.acceleration.z;
		
		scoreTextX.text = "acceleration.x: "  + dir.x;
		scoreTextY.text = "acceleration.y: "  + dir.y;
		scoreTextZ.text = "acceleration.z: "  + dir.z;
		
	}

Hierarchy> Cube> Inspector> AccelerometerTest.js assign GUI Text to public var scoreText

Here the final result:

dir.x = Input.acceleration.x; from 1 to -1 -> example: 0.1234567 or -0.1234567
dir.y = Input.acceleration.y; from 1 to -1
dir.z = Input.acceleration.z; from 1 to -1

unity-001

unity-002

unity-003

To translate the Cube using Accelerometer data (basic):

AccelerometerTest.js


#pragma strict

function Update () 
{
    transform.Translate(Input.acceleration.x, 0, -Input.acceleration.z);
}

To translate the Cube using Accelerometer data (advanced):

AccelerometerTest.js


#pragma strict

	// Move object using accelerometer
	var speed = 10.0;

// Hierarchy DRAG E DROP over var GUI Text in Inspector
var scoreTextX : GUIText;

	function Update () {
		var dir : Vector3 = Vector3.zero; // Shorthand for writing Vector3(0, 0, 0)
		
		dir.x = Input.acceleration.x;
		
		scoreTextX.text = "acceleration.x: "  + dir.x;
		
		// clamp acceleration vector to unit sphere
		if (dir.sqrMagnitude > 1)
			dir.Normalize();
		
		// Make it move 10 meters per second instead of 10 meters per frame...
		dir *= Time.deltaTime;
			
		// Move object
		transform.Translate (dir * speed);
		
	}

unity-004

By |Unity3D, Video Games Development|Commenti disabilitati su Unity 3D Game Engine – Android – Accelerometer – RAW Data – Translate and Object

Unity 3D Game Engine – Android – Accelerometer – Shake – JavaScript

Unity 3D Game Engine – Android – Accelerometer – Shake – JavaScript

Hierarchy:

– Main camera
– GUI Text
– Cube, attach the script ‘CheckShake.js’

CheckShake.js


#pragma strict

// Hierarchy DRAG E DROP over var GUI Text in Inspector
var scoreTextX : GUIText;

var accelerometerUpdateInterval : float = 1.0 / 60.0;

// The greater the value of LowPassKernelWidthInSeconds, the slower the filtered value will converge towards current input sample (and vice versa).
var lowPassKernelWidthInSeconds : float = 1.0;

// This next parameter is initialized to 2.0 per Apple's recommendation, or at least according to Brady! 😉
var shakeDetectionThreshold : float = 2.0;

private var lowPassFilterFactor : float = accelerometerUpdateInterval / lowPassKernelWidthInSeconds; 
private var lowPassValue : Vector3 = Vector3.zero;
private var acceleration : Vector3;
private var deltaAcceleration : Vector3;


function Start()

{
shakeDetectionThreshold *= shakeDetectionThreshold;
lowPassValue = Input.acceleration;
}


function Update()
{

acceleration = Input.acceleration;
lowPassValue = Vector3.Lerp(lowPassValue, acceleration, lowPassFilterFactor);
deltaAcceleration = acceleration - lowPassValue;
    if (deltaAcceleration.sqrMagnitude >= shakeDetectionThreshold)
    {
        // Perform your "shaking actions" here, with suitable guards in the if check above, if necessary to not, to not fire again if they're already being performed.
        scoreTextX.text = "Shake event detected at time "+Time.time;
    }

}

Hierarchy> Cube> Inspector> CheckShake.js> DRAG AND DROP ‘GUI Text’ GameObject over public var scoreTextX

Reference:
http://forum.unity3d.com/threads/15029-Iphone-Shaking?p=206342#post206342

By |Unity3D, Video Games Development|Commenti disabilitati su Unity 3D Game Engine – Android – Accelerometer – Shake – JavaScript