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

How to build a 2D Space shooter with efficiency calculation in Unity3D

In this blog post I’m going to show you how to build a 2D Space shooter with efficiency calculation in Unity3D.

I followed these two blog posts: post #1 and post #2, and updated it for the use with Unity 4.5 and added the counters for number of bullets fired and number of rocks generated and showed the precision efficiency.

You can try my version, or you can download the project on GitHub. Following are the steps on how to make it your self:

    1. Start a new 2D project in Unity3D
    2. Create folders Scripts, Scenes, Prefabs, Textures
    3. Put all the texture assets to Textures folder
    4. Save the (ctrl +s) scene to Scenes folder with some name
    5. Drag background to Hierarchy
    6. Drag ship to Hierarchy
      1. set y to -4
      2. add Rigidbody2D
      3. check IsKinematic (the gravity doesn’t affect it)
    7. Add script to ship:
      #pragma strict
      // A variable that will contain our bullet prefab
      public var bullet : GameObject;
      public var brzina: int;
      var score : int;
      
      function Start(){
          	score = 0;
      }
      
      function Update() {  
          // Move the spaceship horizontally  
          rigidbody2D.velocity.x = Input.GetAxis("Horizontal") * 10;
          rigidbody2D.velocity.y = Input.GetAxis("Vertical") * 10;
      
      	//add support for mobile phone tilting
      	transform.Translate(Input.acceleration.x*Time.deltaTime*20, 0, 0);
          
          if (Input.GetKeyDown("space") || Input.GetMouseButtonDown(0)) {   
          	Instantiate(bullet, transform.position, Quaternion.identity);
          }    
      }
    8. Add bullet to Hierarchy
      1. add Physics2D -> Rigidbody 2D
      2. add script:
        public var speed : int = 6;
        
        // Gets called once when the bullet is created
        function Start () {  
            // Set the Y velocity to make the bullet move upward
            rigidbody2D.velocity.y = speed;
        }
        
        // Gets called when the object goes out of the screen
        function OnBecameInvisible() {  
            // Destroy the bullet 
            Destroy(gameObject);
        }
      3. add bullet to Prefabs folder and delete it from the Hierarchy
      4. drag the bullet from Prefabs folder to the bullet variable in Inspector when the spaceship is selected
    9. Add an enemy (from Textures) to the Hierarchy
      1. add Rigidbody 2D
      2. set IsKinematic
      3. add script:
        // Public variable that contains the speed of the enemy
        public var speed : int = -5;
        
        // Function called when the enemy is created
        function Start () {  
            // Add a vertical speed to the enemy
            rigidbody2D.velocity.y = speed;
        
            // Make the enemy rotate on itself
            rigidbody2D.angularVelocity = Random.Range(-200, 200);
        
            // Destroy the enemy in 3 seconds,
            // when it is no longer visible on the screen
            Destroy(gameObject, 3);
        }
        
        function OnTriggerEnter2D(obj : Collider2D) {  
            var name = obj.gameObject.name;
        
            // If it collided with a bullet
            if (name == "bullet(Clone)") {
                // And destroy the bullet
                Destroy(obj.gameObject);
                
                handleDestroy(gameObject);
            }
        
            // If it collided with the spaceship
            if (name == "spaceship") {
                handleDestroy(gameObject);
            }
        }
        
        function handleDestroy(gameObject: GameObject){
        	gameObject.Find("ScoreText").SendMessage("Hit");
            Destroy(gameObject);
        }
      4. Add enemy from Hierarchy to Prefabs folder and delete it from Hierarchy
    10. Add spawn object to Hierarchy
      1. position it above the background
      2. add script:
      1. public var enemy : GameObject;
        
        // Variable to know how fast we should create new enemies
        public var spawnTime : float = 1.3;
        
        function Start() {  
            // Call the 'addEnemy' function every 'spawnTime' seconds
            InvokeRepeating("addEnemy", spawnTime, spawnTime);
        }
        
        // New function to spawn an enemy
        function addEnemy() {  
            // Variables to store the X position of the spawn object
            // See image below
            var x1 = transform.position.x - renderer.bounds.size.x/2;
            var x2 = transform.position.x + renderer.bounds.size.x/2;
        
            // Randomly pick a point within the spawn object
            var spawnPoint = new Vector2(Random.Range(x1, x2), transform.position.y);
        
            // Create an enemy at the 'spawnPoint' position
            Instantiate(enemy, spawnPoint, Quaternion.identity);
        }
      2. drag enemy prefab to spawn object
    11. For the spaceship, the enemy prefab, and the bullet prefab do the following
      1. add Component -> Physics 2D -> Box Collider 2D
      2. for enemy Box Collider 2D check IsTrigger and this will give you the OnTriggerEnter2D function
    12. Create -> UI -> Text (name it ScoreText)
      1. Canvas -> RenederMode -> World space, no camera
      2. Rect transform – 450×340 (WxH)
      3. Add -> Script -> ScoreScript.js:

        import UnityEngine.UI.Text;
        
        var Counter : int;
        var text : UnityEngine.UI.Text;
        
        function Start () {
        	text = GetComponent(UnityEngine.UI.Text);
        	Counter = 0;
        }
        
        function Update () {    
             text.text = "Kills: "+Counter;
        }   
                 
        function Hit () {            
            Counter++;
        }
    13. Create -> UI -> Text (name it RocksText)
      1. Add -> Script -> RocksScript.js:

        import UnityEngine.UI.Text;
        
        var Counter : int;
        private var text : UnityEngine.UI.Text;
        
        function Start () {
        	text = GetComponent(UnityEngine.UI.Text);
        	Counter = 0;
        }
        
        function Update () {    
             text.text = "Rocks: "+Counter;
        }   
                 
        function RockAdd () {            
            Counter++;
        }
    14. Create -> UI -> Text (name it EffText)
      1. Add -> Script -> EffScript.js:
        import UnityEngine.UI.Text;
        
        private var Kills : int;
        private var Rocks : int;
        private var Eff : float;
        private var text : UnityEngine.UI.Text;
        
        function Start () {
        	text = GetComponent(UnityEngine.UI.Text);
        	Eff = 0;
        	Kills = 0;
        	Rocks = 0;
        }
        
        function Update () {    
             Kills = gameObject.Find("ScoreText").GetComponent(ScoreScript).Counter;
             Rocks = gameObject.Find("RocksText").GetComponent(RocksScript).Counter;
                  
             if (Kills == 0 || Rocks == 0)
             	Eff = 0;
             else
             	Eff = Kills * 1.0f / Rocks * 100;
             	
             text.text = "Eff: " + Eff.ToString("F0") + "%";
        }
CodeProject, Unity3D

How to make a Unity3D Ball Roller game

I followed http://unity3d.com/learn/tutorials/projects/roll-a-ball, and updated the steps for the newest Unity3D currently available (4.5). You can try the game and download the project on GitHub.

  1. Create a new 3D project and save a scene in a Assets/Scenes folder
  2. Game object – 3d object – Plane, and rename to Ground
  3. Transform – Reset -> sets to 0,0,0 origin point of the world
  4. Edit – Frame selected or character F
  5. Hierarchy -> Create -> 3D object -> Sphere, and again Transform – Reset and again Edit – Frame selected, rename it to Player
  6. Hierarchy -> Create -> Light -> Directional light (name it Main Light)
    1. Rotation x 30, y 60
    2. Shadow – Soft
    3. Very high resolution
  7. Duplicate Main Light and reverse the Rotation x -30, y -60
  8. Color – some blue, intensity 0.1, no shadows
  9. We use Folders in Project tab to organize stuff and Empty game objects in Hierarchy tab
  10. Create empty object and rename to Lighting
    1. reset transform origin, drag other lighting related object in here
    2. set the y position to 100 so that you move the lighting up (they are based on rotation and not position so that if you place it high up it’s just a matter of “not getting in the way” and they will still work as expected)
  11. Player object -> add Component -> Physics -> Rigidbody
  12. [Moving the player] Create a Scripts folder. Create a script (on the Player object add Component -> New Script) and place it in this folder
    1. Update() – here goes the game code (before rendering the frame)
    2. FixedUpdate() – here goes the physics code (before performing any physics calculation)
    3. To read an axis use Input.GetAxis with one of the following default axes: “Horizontal” and “Vertical” are mapped to joystick, A, W, S, D and the arrow keys. “Mouse X” and “Mouse Y” are mapped to the mouse delta. “Fire1”, “Fire2” “Fire3” are mapped to Ctrl, Alt, Cmd keys and three mouse or joystick buttons.
    4. Add this script:
      var speed : float;
      function FixedUpdate () {
      	var moveHorizontal = Input.GetAxis("Horizontal");
      	var moveVertical = Input.GetAxis("Vertical");
      	
      	var movement = Vector3(moveHorizontal, 0.0f, moveVertical);
      	
      	rigidbody.AddForce(movement * speed * Time.deltaTime);
      }
  13. [Moving the camera] Raise the camera a little and tilt it by setting the rotation. Make it the child of the player (drag the Main Camera to Player object). If you run the game at this point you will see all went bazinga. So, we can’t have it as a child – detach it. What we can do however is attach a script to the camera and offset it based on the position of the player object:
    1. Add script to Main Camera:

      var player : GameObject;
      private var offset : Vector3;
      function Start () {
          offset = transform.position;
      }
      
      function LateUpdate () {   
          transform.position = player.transform.position + offset;
      }
  14. [Adding the walls] – Add new empty object Walls
    1. Create -> 3D object -> Cube (rename to West Wall) and add it as a child to Walls
    2. repeat for other 3 walls
  15. [Adding collectible objects]
    1. Create -> 3D object -> Cube (rename to Pickup)
    2. Reset transform origin
    3. Scale to 0.5 on all axes
    4. Rotate 45° on all axes
    5. Add a script (Rotator):
      function Update () {
      	transform.Rotate(Vector3(15,30,45) * Time.deltaTime);
      }
    6. Create a new folder called Prefabs in the root directory and drag the Pickup object inside it in order to, well, create a Prefab which you can think of as a variable which you can then access with all its parameters. So, when you clone the prefab object, it will have all the behavior that the cloned prefab has.
    7. Create an empty object and drag the prefab inside it
    8. Set orientation to global mode and duplicate a few of the collectibles
  16. [Collision detection]
    1. Add the tag ‘PickUp’ to the Pickup prefab
    2. Add the following function to the Player object script:
      function OnTriggerEnter(other : Collider){
          if(other.gameObject.tag == 'PickUp')
              other.gameObject.setActive(false);
      }
    3. Set Box collider Is Trigger to true in the Pickup prefab and this gives you OnTrigger function
    4. Unity caches all the static colliders – everytime we move, rotate or scale the static colliders, the Unity will recalculate the cache – takes resources! We can move, rotate or scale dynamic colliders and Unity will not cache them. Any game object with a collider and a rigid body is considered a dynamic object. Any game object with a collider and no rigid body is considered a static object
    5. Add a rigidbody to the Pickup prefab. If you start the game now, the Pickup object will fall to the ground because of the Gravity. You can uncheck the Gravity option, but a better solution is to keep it and check the Is Kinematic option.
    6. Static colliders shouldn’t move – walls and floors
    7. Dynamic colliders can move and have a rigidbody attached
    8. Standard rigid bodies are moved using physics forces and Kinematic rigid bodies are moved using transform object
  17. [Counting picked up object]
    1. Add a new variable to the PlayerController script and increment it in the OnTriggerEnter function
    2. Add a new empty game object
    3. Choose “Add Component” -> “Rendering” -> “GUIText”
    4. Transform position (x,y,z) = (0,1,0)
    5. Anchor – upper left
    6. Alignment – center
    7. Pixel offset – 5,5
    8. Font size – 20
    9. Add the GUIText variable to the PlayerController script:
      public var scoreText : GUIText;
      function SetCountText(){
      	scoreText.text = 'Score: ' + score.ToString();
      }
    10. Do the same with the winText (create object, add the public variable in PlayerController script) and drag it to the Player object
  18. [Publishing the game]
    1. File -> Build Settings
    2. Select the target platform
    3. Click on the Switch platform button
    4. Click on the Buildbutton
  19. [Added bonus]
    1. To create a Physics Material select Assets->Create->Physics Material from the menu bar. Then drag the Physics Material from the Project View onto a Collider in the scene.
    2. This way you can make the walls bounce the ball
Miscellaneou$

100th post

Nothing, just saying 🙂

Ok, jokes aside, this has been a nice journey for me. It all started with the post Carcassonne scoring board application which I decided to post after reading James Clear’s post on why we should make things.

Top 10  popular posts until now:

  • How to get started on the MEAN stack (written for HackHands.com and featured in NodeWeekly)
  • Delving into Node.js and Express web framework (written for HackHands.com)
  • MEAN.io VS MEAN.js and deploying the latter on DigitalOcean (written for HackHands.com)
  • Deploying MongoDB and Node.js application on OpenShift (written for CodeProject.com)
  • How I built my own testable The Answer To Life The Universe And Everything npm module (written for CodeProject.com)
  • Build a font viewer application in WPF without writing any C# code (written for CodeProject.com)
  • Using CasperJS on Webfaction to automatically send emails with attached images via Gmail (written for CodeProject.com)
  • How to delete node_modules folder on Windows machine
  • Enable continuous scrolling by default in Adobe Reader
  • Git push origin master could not read username for http://github.com

 

Programming

Notes from the book Game development with Three.js by Isaac Sukin

My notes from the book Game development with Three.js by Isaac Sukin:

Three.js is usually used with a new technology called WebGL, a JavaScript API for rendering graphics without plugins. The API is based on OpenGL, a desktop graphics API (GL stands for graphics library).

Because it uses the client’s graphics processing unit to accelerate rendering, WebGL is fast! However, many mobile browsers as well as Internet Explorer 10 and below do not support WebGL. Luckily, Three.js supports rendering with the HTML5 Canvas API as well as other technologies such as Scalable Vector Graphics instead.

<!DOCTYPE html>
<html>
	<head>
		<script src="http://cdnjs.cloudflare.com/ajax/libs/three.js/r57/three.min.js"></script>
	</head>
	<body>
		
		<script>
			var camera, scene, renderer;
			var geometry, material, mesh;

			var init = function () {

				renderer = new THREE.CanvasRenderer();
				renderer.setSize( window.innerWidth, window.innerHeight );
				document.body.appendChild( renderer.domElement );

				camera = new THREE.PerspectiveCamera( 95, window.innerWidth / window.innerHeight, 1, 5000 );
				camera.position.z = 900;

				scene = new THREE.Scene();

				geometry = new THREE.CubeGeometry( 100, 100, 100 );
				material = new THREE.MeshNormalMaterial( { color: 0x000000, wireframe: true, wireframeLinewidth: 2 } );

				mesh = new THREE.Mesh( geometry, material );
				scene.add( mesh );
			}

			var animate = function () {

				requestAnimationFrame( animate );

				mesh.rotation.x = Date.now() * 0.001;
				mesh.rotation.y = Date.now() * 0.001;

				renderer.render( scene, camera );

			}

			init();
			animate();
		</script>
	</body>
</html>

The renderer creates a new <canvas> element by default that should be added to the DOM. Avoid changing the canvas’ size with CSS; use the renderer’s setSize method instead, which sets the width and height HTML attributes on the canvas element.

This is because CSS describes the display size but not the render size. That is, if the canvas is rendered at 800 x 600, but the CSS shows it at 1024 x 768, the rendering will be stretched to fill the space just like if you specified the CSS size of an image to be larger than its true size. This can result in distortion and difficulty converting between “screen space” and “canvas space.”

The one last thing we need is a camera object as shown in the following code snippet, which is something Three.js uses to tell the renderer from what perspective the scene should be displayed. If the player was standing in your virtual world and their screen represented what they could see, camera would be their eyes, renderer would be their brain, and scene would be their universe.

All objects are initialized at the position (0, 0, 0), also called the origin. The key here is requestAnimationFrame(), which executes the function passed to it when the browser is ready to paint a new frame. Geometries are instances of THREE.Geometry that define the shape of an object in a scene. They are made up of vertices and faces (which are themselves objects and are accessible through the vertices and faces array properties). Vertices are the THREE.Vector3 objects representing points in three-dimensional space, while faces are the THREE.Face3 objects representing triangular surfaces.

Triangle:

var geo = new THREE.Geometry();
geo.vertices = [
    new THREE.Vector3(0, 0, 0),
    new THREE.Vector3(0, 100, 0),
    new THREE.Vector3(0, 0, 100)
];

geo.faces.push(new THREE.Face3(0, 1, 2));
geo.computeBoundingSphere();

3D:

THREE.Sphere(radius, horizontalSegments = 8, verticalSegments = 6)

THREE.Icosahedron(radius, detail = 0);
THREE.Octahedron(radius, detail = 0);
THREE.Tetrahedron(radius, detail = 0);

THREE.CylinderGeometry(radiusTop, radiusBottom, height, radiusSegments = 8, heightSegments = 1, openEnded= false)

THREE.TorusGeometry(radius, tubeWidth = 40, radialSegments = 8, tubularSegments = 6)

THREE.TorusKnotGeometry(radius, tubeWidth = 40, radialSegments, tubularSegments, p = 2, q = 3, heightScale = 1)

2D:

Plane THREE.PlaneGeometry(width, height, widthSegments = 1, heightSegments = 1)

Circle THREE.CircleGeometry(radius, numberOfSides = 8)

Ring THREE.RingGeometry(innerRadius, outerRadius, radialSegments = 8, ringSegments = 8)

Extruding:

var triangle = new THREE.Shape([
new THREE.Vector2 (0, 50),
new THREE.Vector2 (50, 50),
new THREE.Vector2 (50, 0)
]);
var geometry = new THREE.ExtrudeGeometry(triangle, {
bevelEnabled: false,
amount: 30
});

Custom fonts must be in the typeface.js format (you can convert OpenType and TrueType fonts to Typeface format at http://typeface.neocracy.org/fonts.html). Use the following code to create text geometry:

new THREE.TextGeometry("Text message goes here", {
    size: 30,
    height: 20, // extrude thickness
    font: "helvetiker", // font family in lower case
    weight: "normal", // or e.g. bold
    style: "normal", // or e.g. italics
    bevelEnabled: false
});

Procedural city:

var camera, scene, renderer;

function setup() {
    document.body.style.backgroundColor = '#d7f0f7';
    setupThreeJS();
    setupWorld();
    requestAnimationFrame(function animate() {
        renderer.render(scene, camera);
        requestAnimationFrame(animate);
    });
}

function setupThreeJS() {
    scene = new THREE.Scene();
    camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 1, 10000);
    camera.position.y = 400;
    camera.position.z = 400;
    camera.rotation.x = -45 * Math.PI / 180;
    renderer = new THREE.CanvasRenderer();
    renderer.setSize(window.innerWidth, window.innerHeight);
    document.body.appendChild(renderer.domElement);
}

function setupWorld() {
    // Floor
    var geo = new THREE.PlaneGeometry(2000, 2000, 20, 20);
    var mat = new THREE.MeshBasicMaterial({color: 0x9db3b5, overdraw:true});
    var floor = new THREE.Mesh(geo, mat);
    floor.rotation.x = -90 * Math.PI / 180;
    scene.add(floor);
    // Original building
    var geometry = new THREE.CubeGeometry(1, 1, 1);
    geometry.applyMatrix(new THREE.Matrix4().makeTranslation(0, 0.5,0));

    var material = new THREE.MeshDepthMaterial({overdraw: true});
    // Cloned buildings
    for (var i = 0; i < 300; i++) {
        var building = new THREE.Mesh(geometry.clone(), material.clone());
        building.position.x = Math.floor(Math.random() * 200 - 100) * 4;
        building.position.z = Math.floor(Math.random() * 200 - 100) * 4;
        building.scale.x = Math.random() * 50 + 10;
        building.scale.y = Math.random() * building.scale.x * 8 + 8;
        building.scale.z = building.scale.x;
        scene.add(building);
    }
}

// Run it!
setup();

Fog:

scene.fog = new THREE.FogExp2(0x9db3b5, 0.002);

Only the DirectionalLight and PointLight objects can cast shadows. Casting shadows first requires that we enable shadows on the renderer:

renderer.shadowMapEnabled = true;

For our city scene, we’ll enable shadow receiving for our floor and both casting and receiving for our buildings:

floor.receiveShadow = true;
city.castShadow = true;
city.receiveShadow = true;

Finally, we configure our DirectionalLight object to use shadows:

light.castShadow = true;
light.shadowDarkness = 0.5;
light.shadowMapWidth = 2048;
light.shadowMapHeight = 2048;
light.position.set(500, 1500, 1000);
light.shadowCameraFar = 2500;

// DirectionalLight only; not necessary for PointLight
light.shadowCameraLeft = -1000;
light.shadowCameraRight = 1000;
light.shadowCameraTop = 1000;
light.shadowCameraBottom = -1000;

Earlier, we switched from CanvasRenderer to WebGLRenderer in order to support shadows and fog. As a rule of thumb, WebGLRenderer is faster and has the most features, while CanvasRenderer has fewer features but broader browser support. One particularly nice feature of WebGLRenderer is that it supports antialiasing to smooth out jagged edges. We can enable this for our cityscape by passing the option in to the renderer constructor:

renderer = new THREE.WebGLRenderer({antialias: true});

Already written navigation from examples:

<script src="FirstPersonControls.js"></script>

Add timer:

clock = new THREE.Clock();
controls = new THREE.FirstPersonControls(camera);
controls.movementSpeed = 100;
controls.lookSpeed = 0.1;

Add this to requestAnimationFrame:

controls.update(clock.getDelta());

Clicking on the screen in order to select or interact with something is a common requirement, but it’s somewhat harder than it sounds because of the need to project the location of the click in the 2D plane of your screen into the 3D world of Three.js. To do this, we draw an imaginary line, called a ray, from the camera toward the position where the mouse might be in 3D space and see if it intersects with anything. In order to project, we first need a projector:

projector = new THREE.Projector();

Then we need to register a listener on the click event for the canvas:

renderer.domElement.addEventListener('mousedown', function(event) {
var vector = new THREE.Vector3(
renderer.devicePixelRatio * (event.pageX - this.offsetLeft) /
this.width * 2 - 1,
-renderer.devicePixelRatio * (event.pageY - this.offsetTop) /
this.height * 2 + 1,
0
);
projector.unprojectVector(vector, camera);
var raycaster = new THREE.Raycaster(
camera.position,
vector.sub(camera.position).normalize()
);
var intersects = raycaster.intersectObjects(OBJECTS);
if (intersects.length) {
// intersects[0] describes the clicked object
}
}, false);

The last thing you want when your player is clicking madly to shoot at enemies is for the whole screen to suddenly turn blue because the browser thinks the user is trying to select something. To avoid this, you can either cancel the select event in JavaScript with document.

onselectstart = function() { return false; }

or disable it in CSS:

* {
-webkit-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
}

Colission libraries:

  • Ammo.js is a large but complete library compiled to JavaScript from C++. It is available at https://github.com/kripken/ammo.js/
  • Cannon.js is a smaller library written from scratch in JavaScript and inspired in part by concepts from Three.js. It is available at https://github.com/schteppe/cannon.js
  • Physi.js is a bridge between Ammo or Cannon and Three.js that also runs the physics simulation in a separate thread to avoid blocking the rendering. It is available at https://github.com/chandlerprall/Physijs

Well, tbh, stopped at page 61/100 as the examples from the book didn’t quite work for me so all in all very disappointed with the book in that department. But, as far as the writing and explanations up till this point go I think it was good. Grade: 2.7/5  

Books

Legion: Skin deep – Brandon Sanderson

My favourite quotes from the book Legion: Skin deep by Brandon Sanderson:

Always tell your captives they have more time than they do. It makes them relaxed. Sets them to planning instead of trying to break out immediately. The last thing you want to do is to make them desperate, since desperate people are unpredictable.

Anything that is possible is actually a reality given infinity.

Miscellaneou$

Sleep you must, yoda so says

Post from James Clear here: http://jamesclear.com/better-sleep

In the words of the researchers, sleep debt “has a neurobiological cost which accumulates over time.” After one week, 25 percent of the six-hour group was falling asleep at random times throughout the day. After two weeks, the six-hour group had performance deficits that were the same as if they had stayed up for two days straight. Let me repeat that: if you get 6 hours of sleep per night for two weeks straight, your mental and physical performance declines to the same level as if you had stayed awake for 48 hours straight.

The irony of it all is that many of us are suffering from sleep deprivation so that we can work more, but the drop in performance ruins any potential benefits of working additional hours.

Stack Overflow

Should I use Node.js only or behind Apache or Nginx

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.

I wondered about basically the same quesiton as user 7cows had: In what cases should one prefer to use Node.js only as a server in real deployment? When one does not want to use Node.js only, what plays better with Node.js, Apache or Nginx?

The answer, by pauljz, was:

There are several good reasons to stick another webserver in front of Node.js:

  • Not having to worry about privileges/setuid for the Node.js process. Only root can bind to port 80 typically. If you let nginx/Apache worry about starting as root, binding to port 80, and then relinquishing its root privileges, it means your Node app doesn’t have to worry about it.
  • Serving static files like images, css, js, and html. Node may be less efficient compared to using a proper static file web server (Node may also be faster in select scenarios, but this is unlikely to be the norm). On top of files serving more efficiently, you won’t have to worry about handling eTags or cache control headers the way you would if you were servings things out of Node. Some frameworks may handle this for you, but you would want to be sure. Regardless, still probably slower.
  • As Matt Sergeant mentioned in his answer, you can more easily display meaningful error pages or fall back onto a static site if your node service crashes. Otherwise users may just get a timed out connection.
  • Running another web server in front of Node may help to mitigate security flaws and DoS attacks against Node. For a real-world example, CVE-2013-4450 is prevented by running something like Nginx in front of Node.

I’ll caveat the second bullet point by saying you should probably be serving your static files via a CDN, or from behind a caching server like Varnish. If you’re doing this it doesn’t really matter if the origin is Node or Nginx or Apache.

Caveat with nginx specifically: if you’re using websockets, make sure to use a recent version of nginx (>= 1.3.13), since it only just added support for upgrading a connection to use websockets.

Also, user Matt Sergeant added:

Just to add one more reason to pauljz’s answer, I use a front end server so that it can serve up 502 error pages when I’m restarting the backend server or it crashes for some reason. This allows your users to never get an error about unable to establish a connection.

Page 41 of 51« First...102030«40414243»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