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
CodeProject, Ionic

Posting data from Ionic app to PHP server

TL;DR

This is the simplest example which shows how to POST data from an Ionic app to a PHP server.

The tutorial covering the Ionic version 2 can be found here. The tutorial covering the Ionic version 3 can be found here.

Quickstart

To see it in action:

    1. Clone the finished project from Github
    2. Run ionic serve
  1. You should see something like this:
    ionic_phpDemo

If you want to make it work from your server:

  1. Clone the finished project from Github
  2. Upload the PHP/api.php file to your server
  3. In the www/js/app.js file adjust the link variable to point to your server
  4. Run ionic serve

Step by step on how to create this yourself from scratch

  1. Create a new blank Ionic project with:
    ionic start ionicServerSendTest blank
  2. Copy the following code (you’ll already have the .run() part, the .controller() part is novelty here) in www/js/app.js file:
    // Ionic Starter App
    
    // angular.module is a global place for creating, registering and retrieving Angular modules
    // 'starter' is the name of this angular module example (also set in a <body> attribute in index.html)
    // the 2nd parameter is an array of 'requires'
    angular.module('starter', ['ionic'])
    
    .run(function($ionicPlatform) {
        $ionicPlatform.ready(function() {
            // Hide the accessory bar by default (remove this to show the accessory bar above the keyboard
            // for form inputs)
            if (window.cordova && window.cordova.plugins.Keyboard) {
                cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true);
            }
            if (window.StatusBar) {
                StatusBar.styleDefault();
            }
        });
    })
    
    .controller('AppCtrl', function($scope, $http) {
        $scope.data = {};
    
        $scope.submit = function(){
            var link = 'http://nikola-breznjak.com/_testings/ionicPHP/api.php';
    
            $http.post(link, {username : $scope.data.username}).then(function (res){
                $scope.response = res.data;
            });
        };
    });
  3. On your server, create a api.php file with the following content:
    <?php
        //http://stackoverflow.com/questions/18382740/cors-not-working-php
        if (isset($_SERVER['HTTP_ORIGIN'])) {
            header("Access-Control-Allow-Origin: {$_SERVER['HTTP_ORIGIN']}");
            header('Access-Control-Allow-Credentials: true');
            header('Access-Control-Max-Age: 86400');    // cache for 1 day
        }
    
        // Access-Control headers are received during OPTIONS requests
        if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
    
            if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_METHOD']))
                header("Access-Control-Allow-Methods: GET, POST, OPTIONS");         
    
            if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']))
                header("Access-Control-Allow-Headers:        {$_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']}");
    
            exit(0);
        }
    
    
        //http://stackoverflow.com/questions/15485354/angular-http-post-to-php-and-undefined
        $postdata = file_get_contents("php://input");
        if (isset($postdata)) {
            $request = json_decode($postdata);
            $username = $request->username;
    
            if ($username != "") {
                echo "Server returns: " . $username;
            }
            else {
                echo "Empty username parameter!";
            }
        }
        else {
            echo "Not called properly with username parameter!";
        }
    ?>

    As you can see from the code, the first part is explained in detail in this StackOverflow question, and it basically solves the CORS issue that you would otherwise run into.

    The second part, explained in detail in this StackOverflow question,  deals with the way you POST data from Ionic (basically an AngularJS app) to your PHP server. The gist is that AngularJS POSTs by default in a JSON format, and thus you have to json_decode  the data that comes to your PHP server.

  4. In www/js/app.js file adjust the link variable to point to the file on your server
  5. In www/index.html file copy the following content:
    <!DOCTYPE html>
    <html>
        <head>
            <meta charset="utf-8">
            <meta name="viewport" content="initial-scale=1, maximum-scale=1, user-scalable=no, width=device-width">
            <title></title>
            <link href="lib/ionic/css/ionic.css" rel="stylesheet">
            <link href="css/style.css" rel="stylesheet">
            <!-- IF using Sass (run gulp sass first), then uncomment below and remove the CSS includes above
            <link href="css/ionic.app.css" rel="stylesheet">
            -->
            <!-- ionic/angularjs js -->
            <script src="lib/ionic/js/ionic.bundle.js"></script>
            <!-- cordova script (this will be a 404 during development) -->
            <script src="cordova.js"></script>
            <!-- your app's js -->
            <script src="js/app.js"></script>
        </head>
        <body ng-app="starter" ng-controller="AppCtrl">
            <ion-pane>
                <ion-header-bar class="bar-stable">
                    <h1 class="title">Ionic Blank Starter</h1>
                </ion-header-bar>
    
                <ion-content padding="true">
                    <form ng-submit="submit()">
                        <label class="item item-input item-stacked-label">
                            <span class="input-label">Username</span>
                            <input type="text" name="username" placeholder="enter username" ng-model="data.username">
                        </label>
    
                        <input class="button button-block button-positive" type="submit" name="submit" value="Submit to server">                    
                    </form>
    
                    <div class="card">
                        <div class="item item-text-wrap">
                            Response: <b ng-bind="response"></b>
                        </div>
                    </div>
                </ion-content>
            </ion-pane>
        </body>
    </html>

    Here you basically created a form with an username input field and with a submit button. Using AngularJS ng-submit you’re saying that once the submit button is clicked AngularJS should handle it within the submit() function which you defined in app.js file before. Input username uses  the ng-model to bind to the variable on the $scope so that you can then use it in your submit() function.

  6. Run ionic serve  from the root directory of your Ionic app (I’m sure you know this, but just in case that’s where the folders like www, plugins, scss reside).
CodeProject, NodeJS

Using PM2 to run your Node.js apps like a pro

Previously I wrote about running Node.js apps with Nodemon and Forever but nowdays I’m using the ever so slightly more professional PM2.

Running your Node.js application by hand is, well, not the way we roll. Imagine restarting the app every time something happens, or god forbid application crashes in the middle of the night and you find about it only in the morning – ah the horror. PM2 solves this by:

  • allowing you to keep applications alive forever
  • reloading applications without downtime
  • facilitating common system admin tasks

To install PM2, run the following command:

sudo npm install pm2 -g

To start your process with PM2, run the following command (once in the root of your application):

pm2 start server.js

As you can see from the output shown on the image below, PM2 automatically assigns an App name (based on the filename, without the .js extension) and a PM2 id. PM2 also maintains other information, such as the PID of the process, its current status, and memory usage.

PM2

As I mentioned before, the application running under PM2 will be restarted automatically if the application crashes or is killed, but an additional step needs to be taken to get the application to launch on system startup (boot or reboot). The command to do that is the following:

pm2 startup ubuntu

The output of this command will instruct you to execute an additional command which will enable the actual startup on boot or reboot. In my case the note for the additional command was:

sudo env PATH=$PATH:/usr/local/bin pm2 startup ubuntu -u nikola

If you want to learn more about the additional PM2 options you can take a look at this post.

CodeProject, Programming

Soft Skills: The Software Developer’s Life Manual by John Sonmez

[18.09.2015] edit: I honestly can’t believe it! This awesome book is now also available as an audiobook! Now I’ll be able to listen to this ever so slightly awesome content even in my car! John Sonmez, congratulations!, this is probably the first ever programming related book to be published as an audiobook!

positiveFeedback

I reviewed the book Soft Skills: The Software Developer’s Life Manual by John Sonmez with 5 stars on Amazon with the following comment:

I believe Soft Skills will indeed become every software developers’ life manual, in a similar way as Code Complete 2 is.

I really enjoyed the book, and am recommending it to all my “IT” friends (just lent it today to a co-worker :)) – John Sonmez really poured his whole life experience into this, and for this I thank him since I think we all have something to learn from a man who made almost 50 courses for Pluralsight, wrote a bestseller, retired at 33, was a fitness model, bodybuilding contestant, and who is, well, just pure awesome. Btw, I also found that he’s damn speedy in answering any emails, so kudos for not being a hot headed superstar author as some these days play out to be.

The book is divided in 7 chapters, and it’s packed with awesome content. Those of you who have been following my Books category know that I like to mark the passages that I find valuable from books that I read, like for example:

SoftSkills_highlights

but here I won’t be putting them online since that would be a whole lot portion of the book, and I don’t want to be chased for some copyright issues smileyGlasses. Instead I’ll just show you the images of the chapters and comment a bit about them.

In the first section John talks about topics concerning ones career and steps to take in order to make the most out of it. Topics ranging from how to hack the interview, how to actually set goals, work as a freelancer, and even how to quit your job.

1

In the second section John talks about how to create your blog as a first thing you should do to start marketing yourself. John also has a free email course on how to build a successful blog, so make sure to get that free resource if you’re into starting your own blog, or increasing the views of your existing one.

2

In the third section John talks about why is continuous learning something you signed up for the minute you decided to make programming your calling. Also, he explains his own 10-step process for learning, which he used to learn and produce almost 50 courses on Pluralsight.

3

In fourth section John talks about methods and techniques he uses in order to stay crazily productive as he is. Few of them are KanbanFlow and Pomodoro technique.

4

In the fifth section John shares his own method of how he retired at the age of 33. He seems to be highly influenced by authors such as Robert Kiyosaki, and you can see my notes from his book Rich Dad Poor Dad.

5

In sixth section John talks about the importance of fitness in developers life as a tool for increased productivity and better well-being. Also, he covers few of the tech gear for geeks like me (I love my FitBit).

6

Section seven is all about having the right mental attitude, and I’ll quote one of my favorite authors, Napoleon Hill: “You can do it if you believe you can”. If you’re interested, you can read more Napoleon Hill quotes from my notes from his book Think and Grow Rich.

7

After the book I went on to check out his http://simpleprogrammer.com blog, and what’s awesome is that he gives a free email course on how to build a successful blog. Am currently on week 5, and am really learning some key things on what one should do in order to increase his blog credibility and, well, views. So, hope to see those 100k+ users monthly soon 😉

CodeProject, Quick tips

Share a web service on your local development machine with Localtunnel

I was testing Jenkins and as it doesn’t support localhost addresses I found Localtunnel, which, and I qote,

allows you to easily share a web service on your local development machine without messing with DNS and firewall settings.

Localtunnel will assign you a unique publicly accessible url that will proxy all requests to your locally running webserver.

You can  install it via npm:

npm install -g localtunnel

Then, start your project on some local port (for example 1337), and make sure all works well locally. Now, request a tunnel to your local server:

lt --port 1337

And you should get an output like:

your url is: https://awesome.localtunnel.me

You can use this link now and any requests to that url will be routed to your service on port 1337.

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
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].
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
CodeProject, Unity3D

How to create a Unity3D Brick shooter step by step

Followed this official tutorial, my own version on GitHub, and you can see it in action here (WSAD to move, mouse click to shoot).

Steps on how to create this:

  1. Create a new 3D project
  2. Save the scene as Main
  3. Create -> 3D object -> Plane
  4. Create -> 3D object -> Cube
    1. Add Component -> Physics -> Box collider
    2. Add Component -> Physics -> Rigidbody
    3. Drag and drop this object in the Assets/Prefabs folder
    4. Make duplicates (use snapping to move by using the ctrl key)
    5. Make a row of them (about 8) and then make a new empty object and drag them all into this object
    6. Now duplicate this object and position above (again by using snapping with ctrl key)
  5. Create -> 3D object -> Sphere
    1. Add Component -> Physics -> Sphere collider
    2. Add Component -> Physics -> Rigidbody
    3. Make it into a prefab
    4. Delete it from Hierarchy
  6. On the camera object => Add Component -> Script:
    1. #pragma strict
      
      public var projectile : Rigidbody;
      public var shotPos : Transform;
      public var shotForce : float = 1000f;
      public var moveSpeed : float = 10f;
      
      
      function Update ()
      {
          var h : float = Input.GetAxis("Horizontal") * Time.deltaTime * moveSpeed;
          var v : float = Input.GetAxis("Vertical") * Time.deltaTime * moveSpeed;
          
          transform.Translate(new Vector3(h, v, 0f));
          
          if(Input.GetButtonUp("Fire1"))
          {
              var shot : Rigidbody = Instantiate(projectile, shotPos.position, shotPos.rotation);
              shot.AddForce(shotPos.forward * shotForce);
          }
      }
    2. Drag the Sphere prefab to the projectile
  7. Create empty game object and rename to shotPos
    1. drag and drop it on the camera
    2. reset transform origin
    3. Position y=-0.5, z=1
    4. Rotation x=-15
  8. Drag Camera to shot pos variable in the script
  9. If you want to clean up the bullets after 2 seconds, add script to Sphere prefab:
    function Start () {
    	Destroy(gameObject, 2f);
    }
CodeProject, Unity3D

Unity3D scene changing with fade effect

Followed this official tutorial, my own version on GitHub, and you can see it in action here (click the cube to see the effect).

LevelChangeWithFading.

Steps on how to make this:

  1. Create a new 3D project
  2. Save the scene as Level0
  3. Create -> 3D object -> Cube
  4. Create -> Light -> Directional light
  5. Save this scene and create a new one Level2 and repeat the process just here create two cubes
  6. Create an empty object called FaderObj and attach a new script to it called Fading:
    #pragma strict
    
    public var fadeOutTexture : Texture2D;	// the texture that will overlay the screen. This can be a black image or a loading graphic
    public var fadeSpeed : float = 0.8f;		// the fading speed
    private var drawDepth : int = -1000;		// the texture's order in the draw hierarchy: a low number means it renders on top
    private var alpha : float = 1.0f;			// the texture's alpha value between 0 and 1
    private var fadeDir : int = -1;			// the direction to fade: in = -1 or out = 1
    
    
    function OnGUI()
    {
    	// fade out/in the alpha value using a direction, a speed and Time.deltaTime to convert the operation to seconds
    	alpha += fadeDir * fadeSpeed * Time.deltaTime;
    	// force (clamp) the number to be between 0 and 1 because GUI.color uses Alpha values between 0 and 1
    	alpha = Mathf.Clamp01(alpha);
    	
    	// set color of our GUI (in this case our texture). All color values remain the same & the Alpha is set to the alpha variable
    	GUI.color = new Color (GUI.color.r, GUI.color.g, GUI.color.b, alpha);
    	GUI.depth = drawDepth;																// make the black texture render on top (drawn last)
    	GUI.DrawTexture(new Rect(0, 0, Screen.width, Screen.height), fadeOutTexture);		// draw the texture to fit the entire screen area
    }
    
    // sets fadeDir to the direction parameter making the scene fade in if -1 and out if 1
    public function BeginFade (direction : int)
    {
    	fadeDir = direction;
    	return (fadeSpeed);
    }
    
    // OnLevelWasLoaded is called when a level is loaded. It takes loaded level index (int) as a parameter so you can limit the fade in to certain scenes.
    function OnLevelWasLoaded()
    {
    	//alpha = 1;		// use this if the alpha is not set to 1 by default
    	BeginFade(-1);		// call the fade in function
    }
  7. Add the following script to the Cube object:
    #pragma strict
    
    var counter = 0;
    function Start () {
    
    }
    
    function Update () {
    
    }
    
    function OnMouseDown(){
    	Debug.Log("clicked " + counter++);
    	var fadeTime = GameObject.Find ("FaderObj").GetComponent(FadingJS).BeginFade(1);		
    	
    	yield WaitForSeconds(fadeTime);	
    	
    	GameObject.Find("Cube").renderer.enabled = false;
    	
    	fadeTime = GameObject.Find ("FaderObj").GetComponent(FadingJS).BeginFade(-1);
    	
    	yield WaitForSeconds(fadeTime);	
    	
    	Application.LoadLevel(Application.loadedLevel + 1);	
    }
  8. Drag a 2×2 black png image to the Texture variable in the Fading script.
CodeProject, Unity3D

How to create bouncing balls in Unity3D step by step

Followed this official tutorial: http://unity3d.com/learn/tutorials/modules/beginner/physics/assignments/bouncing-ball

My own version on GitHub, and you can see it in action here (watch for 10 seconds to see what happens with the balls in the way the interact).

Steps to make this:

  1. Create a new empty 3D project
  2. Save the scene as Main.unity
  3. Hierarchy -> Create -> 3D object -> Plane
  4. Hierarchy -> Create -> 3D object -> Sphere
    1. drag it up the y axis
  5. Hierarchy -> Create -> Light -> Directional light
    1. drag it up the y axis above the sphere
    2. set x rotation to 90
  6. Click on the Sphere
    1. Add Component -> Physics -> Rigidbody
    2. Add Component -> Physics -> Sphere collider
  7. Assets -> Create -> Physics material
    1. Set Bounciness to 0.8 (to bounce forever set to 1)
    2. Set Bounce combine to Maximum
    3. drag it to the Material of the Sphere collider of the Sphere object
  8. Create a folder called Prefabs in the Assets folder
    1. Drag the Cube to this folder and delete it from the Hierarchy
    2. Drag the prefab Cube from the Prefabs folder to the Hierarcy and you can now duplicate it with the same behavior
Page 2 of 4«1234»

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