Nikola Brežnjak blog - Tackling software development with a dose of humor
  • Home
  • Daily Thoughts
  • Ionic
  • Stack Overflow
  • Books
  • About me
Home
Daily Thoughts
Ionic
Stack Overflow
Books
About me
  • Home
  • Daily Thoughts
  • Ionic
  • Stack Overflow
  • Books
  • About me
Nikola Brežnjak blog - Tackling software development with a dose of humor
Unity3D

Sharing data between scenes in Unity3D

Here’s I’m going to show you steps on how to share your data between scenes in Unity3D

  1. In the starting scene make a new empty object and name it GameData.
  2. Add a script named GameController with the following content:
    #pragma strict
    
    private var data : Array;
    
    function Awake () {
    	DontDestroyOnLoad (this);
    }
    
    function Start () {
    	data = new Array();
    	
    	GetNewResults();
    }
    
    function GetNewResults(){
    	var www : WWW = new WWW ("http://localhost/check");
    	
    	yield www;// Wait for download to complete
    	
    	var dataJson = JSON.Parse(www.data);
    	var novi = dataJson["data"].Value;
    	data = dataJson["someMoreData"];
    	
    	if (novi == "true"){	
    		Application.LoadLevel(Application.loadedLevel + 1);
    	}
    	else{
    		Debug.Log("false");
    	}
    }
    
    public function getData(){
    	return data;
    }

    The most important part is DontDestroyOnLoad(this) which does not destroy this object once a new scene is loaded.

  3. Then, in another scene, in some script do the following to fetch the data:
    var data = GameObject.Find("GameData").GetComponent(GameController).getData();

     

 

Ionic

Create icons and splash screen automatically with ionic resources

In Ionic framework you can use the

ionic resources

command to automatically generate icons and splash screen of different sizes and for optionally different platforms (iOS, Android).

All you have to do is place the icon.png and splash.png in the resources folder in the root of the application and execute the aforementioned command. Ionic will generate the needed configuration in the config.xml file. More about it on the official blog post.

CodeProject, Unity3D

Quick tip on how to use custom fonts in Unity3D

In this post I’m going to show you how to use custom fonts in Unity3D.

TimerTime

demo  forkMe

  1. Create a new project
  2. Save scene (CTRL + s) and name it whatever you wish
  3. Download some free font from the web (I used Texas Grunge from dafont.com):
    FontImportUnity
  4. Create a new folder called Fonts in the Assets folder and drag the .ttf  file inside
    FontImportUnity_2
  5. Adjust the size of the Camera to 8:
    CameraSize
  6. Hierarchy->Create->UI->TextAddingText
  7. Click on Canvas in Hierarchy and set the Render Mode and select your Render Camera:CanvasRenderMode
  8. Click on Text and change the settings (Rect Transform – resize the text to match the canvas size and drag the anchors in all 4 corners, Text, Font, Best Fit, Max Size):
    FontImportUnity_4
Stack Overflow

When I click the next page in datatables my jquery selectors aren’t working anymore

profile for Nikola at Stack Overflow, Q&A for professional and enthusiast programmers
I’m a big fan of Stack Overflow and I tend to contribute regularly (am currently in the top 0.X%). In this category (stackoverflow) of posts I will will be posting my top rated questions and answers. This, btw, is allowed as explained in the meta thread here.

My question was:

I’m using datatables plugin for jquery to show my data on the page. I have this selector when someone clicks on a row:

$('#myTable tr[class !="tableHeader"]').click(function(){
    alert("clicked!");
}

and everything is OK until I click on the “Next page” which shows me next 10 results – then this click function doesn’t show “clicked” message box anymore no matter which row I click.

I’m guessing that the problem is in a way how these new results (rows in the table) are shown, so please give me some ideas on how to solve this.

 The answer, by ghayes, was:

Use jQuery’s Live function. Live will apply to all elements on the page, even ones that don’t exist yet (I assume this is your issue). Thus, your new rows will be clickable when they are created and added to the DOM.

$('#myTable tr[class !="tableHeader"]').live('click',function(){
  alert("clicked!");
});
CodeProject, Unity3D

How to create a countdown timer and show current time in Unity3D

In this post I’m going to show you how to create a countdown timer and show current time in Unity3D.

TimerTime

demo  forkMe

  1. Create a new 2D project:
    unityCreateNewProject
  2. Optionally download some background image (I used this one) and drag it to the Assets folder:
    assetsFolder
  3. Drag the background image to the Hierarchy:
    Hierarchy
  4. Adjust the size of the Camera to 8:
    CameraSize
  5. Hierarchy->Create->UI->Text:
    AddingText
  6. Click on Canvas in Hierarchy and set the Render mode:
    CanvasRenderMode
  7. Click on Text and change the settings (Positions, Width, Height, Text, Font Site):
    textSettings
  8. Rename the Text to TimerText
  9. Duplicate the TimerText and rename to TimeText:
    duplicate
  10. Change y position of TimeText to -200:positionChange
  11. Hierarchy -> Create -> Create Empty:
    CreateEmpty
  12. Rename it to GameController
  13. Inspector -> Add Component -> New Script (name it Timer and select JavaScript):
    AddScript
  14. Paste the following code:
    #pragma strict
     
     var timer: float = 70;
     var isFinishedLevel : boolean = false;
     public var displayText : UnityEngine.UI.Text;
     public var timeText : UnityEngine.UI.Text;
     
     var minsDisplay : String;
     var secsDisplay : String;
     
     var mySeconds : int = 0;
     
     private var oldTimer : float;
     
     function Start(){
         oldTimer = timer;
     }
     
     function Update()
     {
         if (!isFinishedLevel) {
             timer -= Time.deltaTime;
         } 
         
         CurrentTime();
     }
     
     function CurrentTime() { 
         var dt : System.DateTime = System.DateTime.Now;
         var h : int = dt.Hour; 
         var m : int = dt.Minute; 
         var s : int = dt.Second;
     
         timeText.text = h + ":" + m + ":" + s;
         
         if(mySeconds != s)
         {
             mySeconds = s;
             Timing();
         }
         
     }
     
     function Timing()
     {
         if (timer > 0) {
             //var minsDisplay : String = parseInt( timer / 60 ).ToString();
             minsDisplay = parseInt( timer / 60 ).ToString();
             
             //var secsDisplay : String = parseInt( timer ).ToString();
             secsDisplay = parseInt( timer ).ToString();
              
             if ( (timer - ( parseInt(minsDisplay) * 60)) > 10 ) {
                  secsDisplay = parseInt( timer - ( parseInt(minsDisplay) * 60) ).ToString();
             } 
             else {
                 secsDisplay = "0" + parseInt( timer - ( parseInt(minsDisplay) * 60) ).ToString();
             }
             
             //displayText.text = minsDisplay + " : " + secsDisplay;
         } 
         else {
              timer += oldTimer;
         }
         displayText.text = minsDisplay + " : " + secsDisplay;
     }
  15. Drag TimerText and TimeText to the script from Hierarchy:
    dragging
  16. [le problems] – Run the program, and you’ll run into few issues:
    1. If you open up any other window you will notice that the timer will stop, and continue counting once you return to the Unity window [edit: this seems to be expected behavior and in order to “fix” this, you have to set the “Edit -> Project Settings -> Player -> Run In Background” option (from here)]
    2. TimerText and TimeText are not “ticking off” at the same time [edit: this is now also fixed and the code is updated with the fix]
  17. If someone has info on how to solve this, please comment and I’ll update the post once the solution is found [edit: both issues have been resolved thanks to Unity Answers, I’m just leaving them here for some future reference].
Stack Overflow

jQuery UI Selectable Without Selection Box

profile for Nikola at Stack Overflow, Q&A for professional and enthusiast programmers
I’m a big fan of Stack Overflow and I tend to contribute regularly (am currently in the top 0.X%). In this category (stackoverflow) of posts I will will be posting my top rated questions and answers. This, btw, is allowed as explained in the meta thread here.

My question was:

Given this example here: http://jqueryui.com/selectable/#display-grid I would like to make a selection without the “selection box” that appears when you click ‘n drag. Namely, when I click on number 5 and drag to number 6 and then to 10 I get this:

enter image description here

where in fact what i would like to is drag from 5 to 6 to 10 and have only them selected without 9.

I searched the docs and couldn’t find that option, and my google skills didn’t bring me any luck, and I thought this must have been already done it’s just so happens I can’t grasp it on my own or find an existing solution, so any help here is appreciated (not saying you should do the research for me, am just hoping someone dealt with this before so he can point me to the right direction).

It also could be I’m missing the point in trying to accomplish this with jquery UI but this was the first such example I found that fits (kind of) what I want to accomplish.

 The rather extensive answer, by Dom, was:

First, you might want to hide .ui-selectable-helper or change the CSS:

.ui-selectable-helper{display:none;}

Next, do something like this:

$(function(){var _mousedown =false;
    $('#selectable').selectable({
        start:function(event,ui){
            _mousedown=true;},
        stop:function(event,ui){
            _mousedown=false;
            $('.ui-selected').removeClass('ui-selected');
            $('.selecting').addClass('ui-selected');},
        selecting:function(event,ui){if($('.ui-selecting').length ==1)
                $(ui.selecting).addClass('selecting');

            $('.ui-selecting').removeClass('ui-selecting');
            $('.selecting').addClass('ui-selecting');},
        unselecting:function(event,ui){if($(ui.unselecting).hasClass('selecting'))
                $(ui.unselecting).removeClass('selecting');}});

    $('#selectable').on('mouseenter','.ui-selectee',function(){if(_mousedown)
            $(this).addClass('selecting');});});

DEMO: http://jsfiddle.net/dirtyd77/7UVNS/5/ (HELPER HIDDEN)

http://jsfiddle.net/dirtyd77/7UVNS/6/ (HELPER VISIBLE)

Let me know if you have any questions!


***UPDATE:***

.selectable() is not able to do what you are looking for. However, here is something I created. Hope it helps!

JAVASCRIPT:

$(function(){var _mousedown =false,
        _last=null;    
    $('#selectable li').mousedown(function(){
        _mousedown =true;
        $('.ui-selected').removeClass('ui-selected');
        $('#selectable li').attr('unselectable','on').css('user-select','none');
        $(this).addClass('ui-selecting');}).mouseup(function(){
        _mousedown=false;  
        $('.ui-selecting').addClass('ui-selected').removeClass('ui-selecting');
        $('#selectable li').removeAttr('unselectable style');}).mouseenter(function(){if(_mousedown){if($(this).hasClass('ui-selecting'))
                $(_last).removeClass('ui-selecting');

            $(this).addClass('ui-selecting')}}).mouseleave(function(){if(_mousedown){
            _last =  $(this)[0];
            $(this).addClass('ui-selecting');}});});

DEMO: http://jsfiddle.net/dirtyd77/7UVNS/9/


***UPDATE #2:***

If you want to use this on a mobile device, I recommend changing up the format entirely to avoid any possible pitfalls. Here is how I would go about it:

JAVASCRIPT:

$(function(){var _clicked =false;
    $('#btn_select').click(function(){
        _clicked =false;
        $(this).hide();
        $('#selectable li').removeAttr('unselectable style');
        $('.ui-selecting').addClass('ui-selected').removeClass('ui-selecting');});
    $('#selectable li').click(function(){if(!_clicked){
            _clicked =true;
            $('.ui-selected').removeClass('ui-selected');
            $('#selectable li').attr('unselectable','on').css('user-select','none');
            $('#btn_select').show();}if($(this).hasClass('ui-selecting')){
            $(this).removeClass('ui-selecting');}else{
            $(this).addClass('ui-selecting');}});});

*NOTE: you might want a $('body').click() to act as the end_selection button.

DEMO: http://jsfiddle.net/dirtyd77/7UVNS/13/

Stack Overflow

How to turn off php safe mode in plesk 10?

profile for Nikola at Stack Overflow, Q&A for professional and enthusiast programmers
I’m a big fan of Stack Overflow and I tend to contribute regularly (am currently in the top 0.X%). In this category (stackoverflow) of posts I will will be posting my top rated questions and answers. This, btw, is allowed as explained in the meta thread here.

My question was:

Please tell me how to do this from the Plesk interface (version 10).

Btw, if this is not possible through Plesk 10 interface then please tell me which one of these two files I have to change:

[root@vps ~]# find /-name php.ini
/etc/php.ini
/usr/local/psa/admin/conf/php.ini

edit: Eventually I came to see that my main problem was not the safe mode but the open base dir. The link which helped me to solve that is this: remove openbasedir restriction for a specific domain in plesk which I’ll paste here in case that blog gets pulled off:

If you have an open_basedir restriction that is causing issues with a domain, you can remove the restriction easily. First, put the following text in /home/httpd/vhosts/[domain]/conf/vhost.conf:

<Directory/home/httpd/vhosts/[domain]/httpdocs>
  php_admin_flag engine on 
  php_admin_value open_basedir none
</Directory>

# If there was already a vhost.conf in the directory, then just reload Apache. Otherwise, run the magic wand:

/usr/local/psa/admin/bin/websrvmng -av

# Then bounce Apache:

/etc/init.d/httpd reload

# BUT, if the client has both php4 and php5 things get a little more complicated, and you have to add the "IfModule" directive from the apache syntax, e.g.:

< Directory /var/www/vhosts/domain.com/subdomains/SUBDOMAIN/httpdocs>
< IfModule sapi_apache2.c>
      php_admin_flag engine on
      php_admin_flag safe_mode off
      php_admin_value open_basedir none
< /IfModule>
< IfModule mod_php5.c>
      php_admin_flag engine on
      php_admin_flag safe_mode off
      php_admin_value open_basedir none
< /IfModule>
      Options +Includes -ExecCGI
< /Directory>

# Or if you want to add a new location to open_basedir instead of disabling open_basedir, you would have:

php_admin_value open_basedir "/var/www/vhosts/domain.com/httpdocs:/tmp:/new/path/comes/here"

 

The answer, by Eric G, was:

Go to the control panel for the specific domain where you want to turn off safe mode, click on the Websites & Domains tab. At the bottom will be a listing of the domain names, click on an individual name to see it’s hosting settings. There should be a checkbox for PHP, and another one for whether or not to use safe mode.

See also: https://manage.grabweb.in/knowledgebase.php?action=displayarticle&id=86

Books

The Richest Man in Babylon – George S. Clason

My favourite quotes from the book The Richest Man in Babylon:

A part of all you earn is yours to keep.

Why should so few men be able to acquire all the gold? Because they know how. One may not condemn the man for succeeding because he knows how. Neither may one with justice take away from a man what he has fairly earned, to give to a man of less ability.

If you get paid 10 coins, take out only nine for spending.

A man’s wealth is not in the coins that he carries in his purse, but in the income he builds. The stream of money that comes in constantly whether you work or travel.

That’s what each of us calls necessary expenses will always grow to equal our incomes unless we protest to the contrary. Don’t confuse necessities with desires.

Preceding all accomplishment must be desire, which is strong and definite. The wish to be rich is of little purpose, but to desire 10 pieces of gold is a tangible desire which he can press to fulfillment.

The more wisdom we know, the more we may earn.

That man who seeks to learn more of his craft will be richly rewarded.

Where determination is, the way can be found.

The hungrier one becomes, the clear ones mind becomes.

How can you call yourself a free man when your weakness has brought you here. If a man has in himself a soul of a slave, will he not become one no matter what his birth?

CodeProject, Unity3D

How to build an advanced space shooter in Unity3D

Followed this official tutorial on how to build an advanced space shooter in Unity3D, my own version on GitHub, and you can see it in action here (WSAD to move, mouse click to shoot).

  1. Create a new 2D project, download and import the assets from https://www.assetstore.unity3d.com/en/#!/content/13866
  2. Save a scene in _Scenes folder and name it Main
  3. File -> Build settings -> Web player -> Switch platform
  4. Player Settings… – define the size
  5. Reorder the layout the way you want but remember to save it by clicking the Layout button in the top right corner
  6. Drag Vehicle_play from the Assets->Model folder to the Hierarchy
    1. Rename to player, reset transform origin
    2. Add component -> Physics -> Rigidbody and deselect Use Gravity
    3. Add component -> Physics -> Capsule collider, change direction to Z-Axis and adjust position of X, and check Is Trigger
    4. Click on the y gizmo of the camera and adjust again
    5. In this example the Capsule collider would suffice, but we can add Mesh collider and this is very detailed but we can also drag a predefined Mesh collider from Models folder to Mesh collider -> Mesh variable which is less detailed but sufficent and better than the Capsule collider
      1. To see the mesh collider turn off the Mesh renderer
    6. Add Prefabs -> VFX -> Engines -> engines_player to the player object
  7. Reset camera transform origin
    1. set transform Y to 10, Z to 5 (so that the ship starts at the bottom)
    2. set rotation X to 90
    3. Set Projection to ortographic
    4. Set Size to 10
    5. Set Clear flags to Solid Color
    6. Background black
  8. Edit -> Render settings – property Ambient light set to Black (0,0,0,255) to effectively turn it off
  9. Lights
    1. Main light
      1. Hierarchy -> Create -> Directional light (based on rotation!, not position) and rename accordingly
      2. Reset origin position
      3. Set Rotation X = 20, Y = – 115
      4. Intensity = 0.75
    2. Fill light
      1. Duplicate the Main light and rename accordingly
      2. Rename to Fill light
      3. Reset its rotation only
      4. Set Rotation Y = 115
      5. Set Color to some shade of blue
    3. Rim light
      1. Duplicate the Fill light and rename accordingly
      2. Reset origin position
      3. Color White
      4. Rotation Y = 65, X = -15
      5. Intensity = 0.25
  10. Object organization
      1. Create new empty object (ctrl + shift + n)
      2. Rename to Lights
      3. Rest transform origins
      4. Move the whole Lights object out of the way by setting the position Y = 100
  11. Background
    1. Hierarchy -> Create -> 3D object -> Quad; rename accordingly
    2. Reset transform origin
    3. Set rotation X = 90
    4. Remove the Mesh Collider component
    5. Drag Assets -> Textures -> tile_nebula_green to the Quad object
    6. Scale X = 15, Y = 30
    7. Shaders; difuse – mat, specular – glossy, unlit -> texture is the one we will use since this makes it independent of the lighting system (it displays the image originally as it looks)
    8. Position Y = -10 because it otherwise overlaps with 0,0,0 player object position
  12. Moving the player ship
    1. In the Assets folder create folder Scripts
    2. Click on the player and Add Component -> Script -> name it PlayerController
    3. Drag the created script file to the Scripts folder
    4. You have Update and FixedUpdate. We will use since we are dealing with physics.
    5. #pragma strict
      public var speed = 12;
      
      function FixedUpdate () {
      	var moveHorizontal = Input.GetAxis("Horizontal") ;
      	var moveVertical = Input.GetAxis("Vertical");
      	
      	rigidbody.velocity = Vector3(moveHorizontal, 0, moveVertical) * speed;	
      }
    6. Input.GetAxis returns a number from 0 to 1 that’s why you have to multiply
    7. At this point the player ship can go out of the play area, to fix this, use the Mathf.Clamp function:
      #pragma strict
      
      public class Boundary extends System.Object {
      	public var zMin : float;
      	public var zMax : float;
      	public var xMin : float;
      	public var xMax : float;
      }
      
      public var speed = 10;
      public var boundary : Boundary; 
      
      function FixedUpdate () {
      	var moveHorizontal = Input.GetAxis("Horizontal") ;
      	var moveVertical = Input.GetAxis("Vertical");
      	
      	rigidbody.velocity = Vector3(moveHorizontal, 0, moveVertical) * speed;	
      	
      	rigidbody.position = Vector3(
      		Mathf.Clamp(rigidbody.position.x, boundary.xMin, boundary.xMax),
      		0,
      		Mathf.Clamp(rigidbody.position.x, boundary.zMin, boundary.zMax)
      	);
      }
    8. extends System.Object is used to Serialize the object to be able to be used within other object and visible in the inspector
    9. To add tilting when moving:
      #pragma strict
      
      public class Boundary extends System.Object {
      	public var zMin : float;
      	public var zMax : float;
      	public var xMin : float;
      	public var xMax : float;
      }
      
      public var speed = 10;
      public var boundary : Boundary; 
      public var tilt = 4;
      
      function FixedUpdate () {
      	var moveHorizontal = Input.GetAxis("Horizontal") ;
      	var moveVertical = Input.GetAxis("Vertical");
      	
      	rigidbody.velocity = Vector3(moveHorizontal, 0, moveVertical) * speed;	
      	
      	rigidbody.position = Vector3(
      		Mathf.Clamp(rigidbody.position.x, boundary.xMin, boundary.xMax),
      		0,
      		Mathf.Clamp(rigidbody.position.z, boundary.zMin, boundary.zMax)
      	);
      	
      	rigidbody.rotation = Quaternion.Euler(0, 0, rigidbody.velocity.x * - tilt);
      }
  13. Bullets
    1. Create a new empty object rename to Bolt
    2. Reset transform
    3. Create Quad, reset transform, rename VFX
    4. Add VFX as Child of the Bolt
    5. Rotate X = 90
    6. Drag Textures -> fx_lazer_orange_dff to it
    7. Shader -> Particles -> Additive (you can also use Mobile version)
    8. Add component -> Physics -> Rigidbody, deselect Use gravity
    9. Remove the VFX Mesh collider
    10. Select Bolt and add Capsule colider
    11. Change radius and Direction to Z-axis
    12. Check the Is Trigger checkbox
    13. Add script to Bolt object, name it Mover
    14. Make it a Prefab
    15. Delete it from Hierarchy
  14. Firing Bullets
    1. PlayerController.js:
      #pragma strict
      
      public class Boundary extends System.Object {
      	public var zMin : float;
      	public var zMax : float;
      	public var xMin : float;
      	public var xMax : float;
      }
      
      public var bullet : GameObject;
      
      public var speed = 10;
      public var boundary : Boundary; 
      public var tilt = 4;
      public var waitPeriod = 0.05;
      private var nextFire : float;
      
      function FixedUpdate () {
      	var moveHorizontal = Input.GetAxis("Horizontal") ;
      	var moveVertical = Input.GetAxis("Vertical");
      	
      	rigidbody.velocity = Vector3(moveHorizontal, 0, moveVertical) * speed;	
      	
      	rigidbody.position = Vector3(
      		Mathf.Clamp(rigidbody.position.x, boundary.xMin, boundary.xMax),
      		0,
      		Mathf.Clamp(rigidbody.position.z, boundary.zMin, boundary.zMax)
      	);
      	
      	rigidbody.rotation = Quaternion.Euler(0, 0, rigidbody.velocity.x * - tilt);
      }
      
      function Update(){
      	if (Input.GetButton("Fire1") && Time.time > nextFire){
      		nextFire = Time.time + waitPeriod;
      		Instantiate(bullet, Vector3(rigidbody.position.x, 0, rigidbody.position.z), Quaternion.identity);
      	}
      }
    2. Drag the bullet prefab to the bullet variable on the player script
  15. Cleaning up
    1. Create Cube, rename Boundary
    2. Reset transform origin and place it around the whole game
    3. Turn off Mesh Renderer
    4. Is Trigger on Box collider
    5. Remove the renderer
    6. Add script Destroy:

      function OnTriggerExit(other : Collider)
      {
          Destroy(other.gameObject);
      }
  16. Enemies
    1. Create an empty game object – Asteroids
    2. Reset transform origin, move a bit away along the Z axis
    3. Drag the Asteroid model from the Models folder and place it as a child of the Asteroids empty game object – RTO (reset transform origin from now on)
    4. Click on the EGO (empty game object) and add Physics -> Rigidbody
    5. Deselect Use Gravity
    6. Add -> Physics -> Capsule collider
    7. Add Script:
      public var tumble : float;
      
      function Start () {
      	rigidbody.angularVelocity = Random.insideUnitSphere * tumble;
      }
    8. AngularVelocity – how fast the object is rotating
    9. Remove the AngularDrag which eventually slows the asteroid to a halt (drag – trenje for all you Croatian readers)
    10. Add script DestroyByContact:
      #pragma strict
      
      function OnTriggerEnter (other : Collider) {
      	if (other.tag == "Boundary"){
      		return;
      	}
      		
      	Destroy(other.gameObject);
      	Destroy(gameObject);
      }
    11. Add Tag Boundary to Boundary
  17. Explosions
    1.  Adjust the DestroyByContact script:
      #pragma strict
      
      public var asteroidExplosion : GameObject;
      public var playerExplosion : GameObject;
      
      function OnTriggerEnter (other : Collider) {
      	if (other.tag == "Boundary"){
      		return;
      	}
      	
      	//it will create an explosion on the same position as our asteroid
      	Instantiate(asteroidExplosion, transform.position, transform.rotation);
      	
      	if (other.tag == "Player"){
      		Instantiate(playerExplosion, other.transform.position, other.transform.rotation);
      	}
      	
      	Destroy(other.gameObject);
      	Destroy(gameObject);
      }
    2. Drag the needed explosions from the VFX folder
    3. Drag the Mover script to the Asteroid and set speed to -5
    4. Drag Asteroid to a Prefab folder
    5. Delete it from Hierarchy
  18. Game Controller
    1. Create EGO and rename accordingly
    2. Set tag to GameController
    3. Add script:
      #pragma strict
      
      public var enemy : GameObject;
      public var spawnValues : Vector3;
      
      
      function Start () {
      	SpawnWaves();
      }
      
      function SpawnWaves(){
      	
      	var spawnPosition = Vector3(Random.Range(-spawnValues.x, spawnValues.x), spawnValues.y, spawnValues.z);
      	var spawnRotation = Quaternion.identity;
      	
      	Instantiate(enemy, spawnPosition, spawnRotation);
      }
    4. Outside set values for spawnValues to 6, 0, 18
  19. Add wave of enemies
    #pragma strict
    
    public var enemy : GameObject;
    public var spawnValues : Vector3;
    public var enemyCount : int;
    public var waitForEnemy : float;
    public var waitForPlayer : float;
    public var waveWait : float;
    
    function Start () {
    	SpawnWaves();
    }
    
    function SpawnWaves(){
    	yield WaitForSeconds(waitForPlayer);
    	
    	while (true){
    		for (var i=0; i<enemyCount; i++){
    			var spawnPosition = Vector3(Random.Range(-spawnValues.x, spawnValues.x), spawnValues.y, spawnValues.z);
    			var spawnRotation = Quaternion.identity;
    		
    			Instantiate(enemy, spawnPosition, spawnRotation);
    			yield WaitForSeconds(waitForEnemy);
    		}
    	}
    	
    	yield WaitForSeconds(waveWait);	
    }
  20. Destroying explosion animations
    1. Add new script DestroyByTime

      #pragma strict
      
      public var aliveTime : float;
      function Start () {
      	Destroy(gameObject, aliveTime);
      }
    2. Set this script on all of the explosion prefabs
    3. Set AliveTime to 2
  21. Audio
    1. Drag the Audio files to appropriate Explosion Prefabs
    2. For a weapon_player – drag it to a Player object in Hierarchy and remove the Play on Awake
    3. Update the PlayerController script to:
      function Update(){
      	if (Input.GetButton("Fire1") && Time.time > nextFire){
      		nextFire = Time.time + waitPeriod;
      		Instantiate(bullet, Vector3(rigidbody.position.x, 0, rigidbody.position.z), Quaternion.identity);
      		
      		audio.Play();
      	}
      }
    4. Drag music_background to GameController
    5. Select Loop and Play on Awake
    6. Adjust the volumes
      1. Player 0.5
      2. Game Controller 0.5
  22. Displaying score
    1. Create -> UI -> Text, rename to ScoreText
    2. Set correct Rect Transform
    3. In the GameController script add:
      #pragma strict
      
      public var enemy : GameObject;
      public var spawnValues : Vector3;
      public var enemyCount : int;
      public var waitForEnemy : float;
      public var waitForPlayer : float;
      public var waveWait : float;
      
      public var scoreText : UnityEngine.UI.Text;
      private var score : int;
      
      function Start () {
      	score = 0;
      	updateScore();
      	SpawnWaves();
      }
      
      function SpawnWaves(){
      	yield WaitForSeconds(waitForPlayer);
      	
      	while (true){
      		for (var i=0; i<enemyCount; i++){
      			var spawnPosition = Vector3(Random.Range(-spawnValues.x, spawnValues.x), spawnValues.y, spawnValues.z);
      			var spawnRotation = Quaternion.identity;
      		
      			Instantiate(enemy, spawnPosition, spawnRotation);
      			yield WaitForSeconds(waitForEnemy);
      		}
      	}
      	
      	yield WaitForSeconds(waveWait);	
      }
      
      function updateScore(){
      	scoreText.text = "Score: " + score;
      }
      
      function IncreaseCount(){
      	score ++;
      	updateScore();
      }
    4. In the DestroyByContact:
      #pragma strict
      
      public var asteroidExplosion : GameObject;
      public var playerExplosion : GameObject;
      private var gameController : GameController;
      
      function Start(){
      	var gameControllerObject : GameObject = GameObject.FindWithTag("GameController");
      	if (gameControllerObject != null){
      		gameController = gameControllerObject.GetComponent(GameController);
      	}
      	else{
      		Debug.Log("oops");
      	}
      }
      
      function OnTriggerEnter (other : Collider) {
      	if (other.tag == "Boundary"){
      		return;
      	}
      	
      	//it will create an explosion on the same position as our asteroid
      	Instantiate(asteroidExplosion, transform.position, transform.rotation);
      	
      	if (other.tag == "Player"){
      		Instantiate(playerExplosion, other.transform.position, other.transform.rotation);
      	}
      	
      	gameController.IncreaseCount();
      	
      	Destroy(other.gameObject);
      	Destroy(gameObject);
      }
    5. Drag the ScoreText object to form the reference to it in the GameController
  23. Ending the game
    1. Create an empty game object and rename it to DisplayText
    2. Rest transform origin
    3. Add ScoreText to it (drag the Canvas containing it)
    4. Create new UI -> Text (rename to RestartText), and place it in the upper right corner
    5. Create new UI -> Text (rename to GameOverText)
    6. Update the script to:
      #pragma strict
      
      public var enemy : GameObject;
      public var spawnValues : Vector3;
      public var enemyCount : int;
      public var waitForEnemy : float;
      public var waitForPlayer : float;
      public var waveWait : float;
      
      public var scoreText : UnityEngine.UI.Text;
      public var restartText : UnityEngine.UI.Text;
      public var gameOverText : UnityEngine.UI.Text;
      
      private var restart : boolean;
      private var gameOver : boolean;
      
      private var score : int;
      
      function Start () {
      	restart = false;
      	gameOver = false;
      	
      	restartText.text = "";
      	gameOverText.text = "";
      	
      	score = 0;
      	updateScore();
      	SpawnWaves();
      }
      
      function Update(){
      	if (restart){
      		if (Input.GetKeyDown(KeyCode.R)){
      			Application.LoadLevel(Application.loadedLevel);
      		}
      	}
      }
      
      function SpawnWaves(){
      	yield WaitForSeconds(waitForPlayer);
      	
      	while (true){
      		for (var i=0; i<enemyCount; i++){
      			var spawnPosition = Vector3(Random.Range(-spawnValues.x, spawnValues.x), spawnValues.y, spawnValues.z);
      			var spawnRotation = Quaternion.identity;
      		
      			Instantiate(enemy, spawnPosition, spawnRotation);
      			yield WaitForSeconds(waitForEnemy);
      		}
      		
      		if (gameOver){
      			restartText.text = "R to restart";
      			restart = true;
      			break;
      		}
      	}
      	
      	yield WaitForSeconds(waveWait);	
      }
      
      function updateScore(){
      	scoreText.text = "Score: " + score;
      }
      
      function IncreaseCount(){
      	score ++;
      	updateScore();
      }
      
      function GameOver(){
      	gameOver = true;
      	gameOverText.text = "Game over!";
      }
    7. Drag the text object to form a reference in GameController object
    8. Update the DestroyByContact with:
      if (other.tag == "Player"){
      		Instantiate(playerExplosion, other.transform.position, other.transform.rotation);
      		gameController.GameOver();
      	}
  24. Deploy the game
    1. File -> Build settings
    2. Web Player
    3. Build
Quick tips

How to find unread emails in Gmail

As you can see in the featured image, to find unread emails in Gmail, just search for is: unread and you will get all of your unread emails.

You can combine this, for example, to only find unread emails in a certain label: label:myStuff is:unread

Page 40 of 51« First...102030«39404142»50...Last »

Recent posts

  • Discipline is also a talent
  • Play for the fun of it
  • The importance of failing
  • A fresh start
  • Perseverance

Categories

  • Android (3)
  • Books (114)
    • Programming (22)
  • CodeProject (35)
  • Daily Thoughts (77)
  • Go (3)
  • iOS (5)
  • JavaScript (127)
    • Angular (4)
    • Angular 2 (3)
    • Ionic (61)
    • Ionic2 (2)
    • Ionic3 (8)
    • MEAN (3)
    • NodeJS (27)
    • Phaser (1)
    • React (1)
    • Three.js (1)
    • Vue.js (2)
  • Leadership (1)
  • Meetups (8)
  • Miscellaneou$ (77)
    • Breaking News (8)
    • CodeSchool (2)
    • Hacker Games (3)
    • Pluralsight (7)
    • Projects (2)
    • Sublime Text (2)
  • PHP (6)
  • Quick tips (40)
  • Servers (8)
    • Heroku (1)
    • Linux (3)
  • Stack Overflow (81)
  • Unity3D (9)
  • Windows (8)
    • C# (2)
    • WPF (3)
  • Wordpress (2)

"There's no short-term solution for a long-term result." ~ Greg Plitt

"Everything around you that you call life was made up by people that were no smarter than you." ~ S. Jobs

"Hard work beats talent when talent doesn't work hard." ~ Tim Notke

© since 2016 - Nikola Brežnjak