Thursday 14 April 2016

Unity - Top down Camera View



To this point i have become accustomed to the unity IDE, how to import assets in how to create a scene with a terrain/sky box/ simple objects.

The first challenge was making these objects interact and behave in certain ways inside the environment.

The first key thing to learn was how to apply certain components to a game object, which allows physics characteristics like "Rigidbody" to be added to a gameobject. In doing this, we can then set its box collider > material attribute as "Bouncy".

From here the next challenge was how to record & destroy what this cube bounced off of. In comes the need to learn to script.

Unity will allow you to work with JavaScript or with C# (there are more, but this is all myself and seemingly most other are concerned with). As i began learning some JS with my Aurellia/node attempt, i thought i would try to write all my beginner scripts in BOTH languages to see if i could get both working. (this is useful for when certain scripts are only available in 1 language, but you would rather convert it to another)

First i learned to display what objects were in contact, keep a count of how many a type of object was hit and then implementing the find and destroy method. Additionally, how to spawn a prefab object into the world given set time and how to apply a force in a particular direction upon a key press were integrated into this "game" -> the result was actually relatively fun!

I then built this to my android phone to see how it behaved. The result was not great, the keystrokes i had assigned (space) were not converted in the build, and there was no camera movement ability (part of me hoped this would be automatic)

So now challenge is to set my camera up to be a suitable view (RTS style, like mentioned in previous posts) and be responsive to touch gestures. This will also include some getting use to setting up events for touches.

So far I have tried building my own script for the camera. Realising do not yet know enough, i went to find some examples out there. So far from searching the unity forums, stackoverflow, youtube etc, i have found a number of scripts that seem relevant. Problem is: the ones that work, barely work in the right way, and the rest just plain don't work, Further understanding is needed before I can get these scripts working, and then learn enough from them to build my own.

It SEEMS the main problem i am having with my scripts not working is "nullReferenceException: Object reference not set to an instance of an object" in my update() with the common aspect being Camera is mentioned.

private Camera _camera;

void Start () {
//retrieveing pricate variables
_camera = Camera.main;
}

void Update () {
//checked if we want to Update zoom sensitivity
if (updateZoomSensitivity) {
//set move sensitiy x&y to orthographics size / 5 (arbitary number)
moveSensitivityX = _camera.orthographicSize / 5.0f;
moveSensitivityY = _camera.orthographicSize / 5.0f;
}

**or**

Camera cam;

void Awake()
{
cam = Camera.main;
}
void Update ()
{
if (Input.touchCount == 0) {
oldTouchPositions [0] = null;
oldTouchPositions [1] = null;
} else if (Input.touchCount == 1) {
if (oldTouchPositions [0] == null || oldTouchPositions [1] != null) {
oldTouchPositions [0] = Input.GetTouch (0).position;
oldTouchPositions [1] = null;
} else {
Vector2 newTouchPosition = Input.GetTouch (0).position;

cam.transform.position += cam.transform.TransformDirection ((Vector3)((oldTouchPositions [0] - newTouchPosition) * cam.GetComponent<Camera> ().orthographicSize / cam.GetComponent<Camera> ().pixelHeight * 2f));

oldTouchPositions [0] = newTouchPosition;
}
}
}



** Update** this was fixed by simply ensuring the camera object the script was attached to was the MainCamera.

The script i am currently using, which seems to give the best results with an orthographic view is:

using UnityEngine;
using System.Collections;

public class COCcam : MonoBehaviour {

public float moveSensitivityX = 1.0f;
public float moveSensitivityY = 1.0f;
public bool updateZoomSensitivity= true;
public float orthoZoomSpeed = 0.05f;

public float minZoom = 1.0f;
public float maxZoom = 20.0f;
public bool invertMoveX = false;
public bool invertMoveY = false;
private Camera _camera;

void Start () {
//retrieveing private variables
_camera = Camera.main;
}

void Update () {
//checked if we want to Update zoom sensitivity
if (updateZoomSensitivity) {
//set move sensitiy x&y to orthographics size / 5 (arbitary number)
moveSensitivityX = _camera.orthographicSize / 5.0f;
moveSensitivityY = _camera.orthographicSize / 5.0f;
}

//get touches that are on screen
Touch[] touches = Input.touches;

if (touches.Length > 0) {

//single touch(move)
if (touches.Length == 1) {

if (touches [0].phase == TouchPhase.Moved) {   //returns phase of current touch
//obtains delta pos of touch -> difference between touch position of the current/previous frame
Vector2 delta = Input.touches[0].deltaPosition;

//variables for position x / y
float positionX = delta.x * moveSensitivityX * Time.deltaTime;
//check if we are inverting, as per public bools.
//if invertmoveX is true then it will equal the same. IF not, it'll equal posX * -1, inverting it.
positionX = invertMoveX ? positionX : positionX * -1;
float positionY = delta.y * moveSensitivityY * Time.deltaTime;
positionY = invertMoveY ? positionY : positionY * -1;

//set camera's tranform position to = new vector 3 at position x, y, z
_camera.transform.position += new Vector3 (positionX, positionY, 0);
}
}

//double touch (zoom)
if (touches.Length == 2) {

Touch touchOne = touches [0];
Touch touchTwo = touches [1];

//to get the posiiton from the PREVIOUS touch in the previous frame.
//subtract touch pos from touch delta
Vector2 touchOnePrevPos = touchOne.position - touchOne.deltaPosition;
Vector2 touchTwoPrevPos = touchTwo.position - touchTwo.deltaPosition;

//FIND MAGNITUDE OF PREVIOUS TOUCH VS CURRENT TOUCHES
float prevTouchDeltaMag = (touchOnePrevPos - touchTwoPrevPos).magnitude;
//now the current touch dleta magnitude
float touchDeltaMag = (touchOne.position - touchTwo.position).magnitude;
//difference between
float deltaMagDiff = prevTouchDeltaMag - touchDeltaMag;

//set cam's ortho size -> the delta mag * public variable at top.
_camera.orthographicSize += deltaMagDiff * orthoZoomSpeed;
//clamp values between min/max zoom defined at top.
_camera.orthographicSize = Mathf.Clamp(_camera.orthographicSize, minZoom, maxZoom);
}
}
} //close update
} //close class



(deeper tutorials into any of the above can follow if there is enough interest!)


Friday 8 April 2016

April Update - No .NET+Aurelia | Unity vs Three.js

For now the idea of using Visual Studio as my environment along with integrating Aurelia into .net MVC SPA has been abandoned.

This is mostly as there is much conflicting information/versions and honestly i don't know enough to trouble shoot it yet. Problems setting up the environment took longer than expected, and i am not confident that i am "bug-free" moving forward. Given the time restraints of this project, I feel this is a major aspect to be considered. However, this was not a lost learning experience! I learned a lot about the differences between typescripts/es6, the workings of frameworks in general/Aurelia/ .net / MVC/ SPA./ Visual Studio/ Node package Manage (NPM)/ JSPM / Gulp .


So the decision is between:
1) Aurelia + Three.js. implemented as a web app
2) Unity deployed on Android.

To this end i

------------------------------------------------------------------------------------------------------------------
1)For the meantime when working with  with Aurelia, i will use it more independently and in a more basic way. I.e using gulp watch to compile and launch a dummy server and using Sublime (insert: text editor of your preference). I will focus on the "front end" aspect first, using simulated database calls and build up from there.

I believe i have Three.js integrated into a working prototype with Aurelia. Now the challenge would be to learn the three.js framework, something which i have ZERO experience with (never touched 3d of any sort!)



2) Again, similar to above, i have unity downloaded and installed on Visual Studio (not so hard as it is supported by microsoft... a guide on doing this to come in the future)  and again, i have ZERO experience with game design/Unity


---------------
So, the next steps are to do some small demo projects in both Unity and in Three.js looking at various tutorials and seeing which one I gravitate towards more! 

The next guides will be my attempts at learning these :)

Sunday 3 April 2016

Aurelia with C#

set up asp.net mvc project

add aurelia view to home,

add aurellia ActionResult method in home controller.. re map routing so aurelia opens first.

right click project solution and open the containing folder... using right cick run the cmd prompt from the rot directory of the project.

   jspm init  (yes to everything)
   jspm install aurelia-framework
   jspm install aurelia-bootstrapper

now aurellia view file acts as aurellia index... show all files in solution explorer.
right click config.js and "include"
jspm_packages not necessary to add.. but we will drag system.js & the config.js into the aurellai page to <script> link at top.

we will then <script>System.import("aurelia-bootstrapper")

<div aurelia-app="main"></div> - this tells where the aurelia app content will display
                   right click project at top of solution explorer - add> javascript file, name it main.
paste this in:
export function configure(aurelia) { aurelia.use .standardConfiguration() .developmentLogging(); aurelia.start().then(() => aurelia.setRoot()); }

this will set the root to app.js.. which we now create.... Like with the main.js file, add > app.js
            export class App{} // shell for now just to allow running
now add app.html page in the same way... and clear the auto generated code.

right click project>properties>web>select "specific page" and type "/"

     for now we can type <template>Aurelia has started.</template> and run it to confirm we see this message.



































































Wednesday 16 March 2016

SPA - single page application

Definition of a page in SPA:

When the app starts, it is the sent to the browser by the server. All presentation logic is on the client after the page initially loads .
The client, not the server, determines what the app does with the SPA and composes app pages from the HTML templates (fragments) and data which are downloaded asynchronously as needed.
The server has no logic for user interface/ no UI state but instead provides resources to the client. First by providing the initial HTML shell, then in response to client HTTP requests for data (which can be HTML templates, JSON, JS or CSS)

By using Views we will introduce the ability to "change page" while remaining on the same actual page that was initially served to us from the server.

Saturday 12 March 2016

Getting started with Aurelia/node

Get Node.js - download version from node.js website.  -- full guide here

Get JSPM.io pakcage manager (like bower etc)
use node to install JSPM from the command line (windows)
npm install jspm -g
then
jspm init
(might need to return to set the following, if choose the defaults)
Sets up the package.json and configuration file. Note jspm init happens automatically if you try installing into an empty project too.
  • baseURL: This should be set to the public folder where your server will serve from, relative to the package.json file.Defaults to the package.json folder itself.
  • jspm packages folder: The folder where jspm will install external dependencies.
  • Config file path: The jspm config file for your application. Should be within the baseURL and checked in to version control.
  • Client baseURL: The URL from the browser where the public folder is hosted.
  • Transpiler: Change this option at any time with jspm dl-loader babel. Custom transpilation options can also be set through babelOptions or traceurOptions in the jspm config file.
If you ever need to reset any of these properties, you can modify the package.json, which will update the configuration when you next run jspm install or jspm init to refresh.
It is possible to run through the above prompts again at any time with jspm init -p.
------------------
get the Aurelia skeleton navigation (a starting template) and FOLLOW THE README
--download the zip and THEN choose which version you want (typescript, es6, .net etc)

-------------------

You can also link Visual Studio with node to get all the benefits while writing your code.
See here
Microsoft + Node.js Tips & Tricks
General read me and installation guide 
nodejstools/wiki (includes work around for MAX_PATH error)
Package intelisense for VS
Azure Node.js dev center
Web Essentials 2015.1
Bundler & Minifier - for bundling and minifying JS, CSS and HTML files
Web Compiler - for compiling LESS, Sass, Scss, (Iced)CoffeeScript and JSX files
Image Optimizer - for lossless optimization of PNG, JPG and GIFs
Web Analyzer - for static code analysis (linting) of JS, TS, CSS and JSX files 

-----------------------


Starting a new Projects: 
See here for aurelia getting started page
and here for a video explaining aurelia and walking through the set up a bit.

open up a html file in Visual studio (this can be imported by going to file - add existing website -> point it to your folder
in your html file, in the body, type:
<script src="jspm_packages/system.js"></script>    -- this links the system.js file, this allows import of assest. System.import...

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


UI comes in 2 parts: View(HTML rendered into DOM) and View Model(written in Javascript which provides data/behaviour to the view). Databinding links both together and allows updating.



Note: when using TypeScript, Typically the first step in any new project is to add in a tsconfig.json file. This defines the TypeScript project settings such as the compiler options and the files that should be included. To do this, open up the folder where you want to store your source and add in a new file named tsconfig.json. Once in this file IntelliSense will help you along the way.


Friday 11 March 2016

.Net vs MEAN stack

Good article https://www.airpair.com/mean-stack/posts/developers-moving-dotnet-to-mean


Saturday 5 March 2016

JavaScript framworks

Top JavaScript Frameworks, Libraries and Tools and When to Use Them 

(beware that frameworks < flexible than libraries)

Isomorphic JS apps can run both client-side & server side (bankend and front end in the same code). List of all the new isomorphic librarries and frameworks

webcomponents.js

  • Meteor - isomorphic

  • Underscore &lodash - provides a whole suite of utility functions without monkey patching the built-in JavaScript objects. Both libraries provide over 100 functional helpers and other specialized goodies; including functions like map, filter, invoke, reduce, template, throttle, bind, extend, pick, clone

  • Aurelia

complete framework (built using knockout/backbone)                 

  • can easily use React.js within Aurelia
  • full-stack SPA framework with support for ECMAScript 6 syntax (as well as a Gulpfile with customised build system for transpiling your ES6 down to ES5 compatible code).  supports all forms of alternative abstraction syntax out of the box like TypeScript, AtScript and even CoffeeScript
  • Variable binding is simple. with just similar syntax to Javascript itself.
    • <input type="text" value.bind="firstName"> <a href.bind="url">Aurelia</a>
  • You can explicitly specify the type of binding you are using
    • <markdown-editor value.two-way="markdown"></markdown-editor>
.. you are learning ES6 and not so much the framework itself. This means all future frameworks that use ES6 will leverage your existing ES6 knowledge which means if you choose to learn Aurelia, most aspects of it should apply to another framework. - source
Because Aurelia does not replace your HTML or parse it any differently than your browser does without Aurelia, it allows you to use any third party library or plugin inside of your Aurelia application without worrying about it messing with anything.

Aurellia with firebase example ...  aurellia/firebase plugin

Learning through examples - trello page 
building a treeview
I KILL NERDS - POSTS ABOUT AURELLIA 
CODE SNIPPETS GITHUB LINK
How to add a tab (or other) UI component with Aurelia

Configure Aurelia Project using Visual Studio

  • three.js

render a scene with a camera and a mesh. camera is like the view source. each mesh has a genomeyry aND A MATERIAL.
EVERYTHING IN THE SCENE IS THEN PASSED TO THE RENDEREER AND THIS WILL PROJECT ALL 3D TO A 2D IMAGE FOR IEWING. 

has examples ... (webgl)

May need to run a local server.

Blender with three.js plugin for editing 3d models 

https://youtu.be/HwkGTYRopYg?t=349


  • Node.Js

When building a website, code willbe developed that will run on the server to read and write to the database, to generate web pages and respond to other client requests (like expanding text box instead of loading a new page etc). Node.js allows use of Javascript to do this, by loading the JS code on a server & executing it. (AKA "server side")

"Client side" javascript (older but still common) is what is delivered to the browser FROM the server, as textual code, and is then executed by the CLIENT'S browser. MAny website have client JS running and its benefit is it allows dynamic web pages.

Client side JS frameworks like EmberJS or AngularJS are being used to run entire applications completely on the client's browser. The is done by using a web server (usually within Node.js) to statically serve the front end application content (i.e. the HTML, JS, etc...) and only using Node as a sort of REST API to be called for external information such as database calls and the like.

An advantage to this can be certain actions will not require a full reload of the page (e.g liking a post on facebook, or expanding a comment section etc) and the application can update it's various components dynamically, only getting what it needs when it needs it. 

This can mean the Node.js Server does not need to preprocess templates into HTML code every time the user wants to do something non trivial. Server/client configuration becomes more flexible since communication between the client/server are only HTTP requests & responses.

Javascript via node.js is rising in popularity as a server side language. Alternatives being PHP, Ruby on Rails, Java, Go and Python.  Node.js allows you to run the same language on both client and server, but this doesn't always equate to a huge advantage as conversion to text/binary data is still required when passing things around.

Note: Anything that be can done in node.js can be done in these other languages and server-side frameworks. Using Python doesn't prevent doing anything that could be done in node.js.

  • Angular 

(1 vs version 2) - front end framework   static and requires some kind of back-end or API. (think: MEAN stack: Mongo, Express, Angular, Node)

 inlining HTML is "ugly" and confusing compared to React - instead, must group controller through an ng template (<script type = "text/ng-template" id ="comment-box.htm">) -

..</head> <body> <h1> Hello<h1> <div>
bn:comment-box url="/comments.json" poll-interval="2000"> </div>
<script type="text/javascript">
                           ---// to manage the comment box // --
angular.module ("Tutorial").directive("bnCommentBox", function(){
                           ---// return direcive configuration object// --
return({ controller: Controller, scope:{ url:"@", pollInterval: "@"}. templateURL:    });
                            ---// to manage the comment box view-model // --
funcntion Controller ($scope, $http) {
$scope.comments = [];          ---// collection comments to render// --
setInterval (loadRemoteData, $scope.pollInterval);       ---// poll URL for new content// --
loadREmoteData():

Philosopy to only render when necessary  means state must be managed more implicity;


Very popular, flexible, lot of eatures, 800 3rd party modules, big community (backed by google)

2 way data binding (
The problem with Angular is even though it simply adds a layer over the top of traditional HTML, you have to learn its abstractions; directives, controllers, services, factories and the way it expects things to be done. Then you need to understand how to do things “the Angular way”, how the $digest cycle works, scoping and issues with nested scoping, communicating between components and other various aspects of Angular that add to the learning curve. - source
There are basically five pillars of AngularJS:

  • Directives
    • The idea behind directives is that you're able to create your own HTML elements with custom functionality. Think about how we write HTML pages: we use different tags to represent different behaviors: `<a>` tags for links, `<p>` tags for paragraphs. 

      If we are using HTML5 we might use the new `<audio>` tags for audio or `<video>` tag for a video player.

      But what if we want to write our own custom tag with our own custom functionality. (Say, a `<weather>` tag or a `<map>` tag.) Then we'd use directives! 
    • more about the details of writing directives, see this post about directives by ng-newsletter.
  • Controllers
    • Angular controllers are used to organize functionally across a group of DOM elements. (When I say, "DOM elements", I just mean a group of HTML tags). 

      The idea is that we can organize our functionality into modules of code and it helps contain functionality in one place. This helps keep a project maintainable as it grows. 
    • video on AngularJS controllers.
  • Scopes
    • AngularJS uses scopes to communicate between components - especially between javascript (in controllers) and our HTML (our "view"). Scopes are the glue between our code.
    • Code examples, part 2 of  "AngularJS beginner to expert series"  
  • Services
    • Sometimes we want to share code across different controllers in our code. In Angular we use services to perform this functionality. Services are singleton objects that perform tasks that are common to several areas of the system.
    • AngularJS guide on AngularJS services.
  • Dependency Injection
    • How a particular part of the code gets it's dependencies. Dependency Injection (DI) is analogous to `require` in node.js or ruby or `import` in Java. The idea is we're just declaring what dependencies we need.  AngularJS makes this really easy.
 3 learning sources:
1. ng-newsletter's post on How to Learn AngularJS
2. ng-newsletter's Beginner to expert 7 step series 
3. egghead.io - Learn AngularJS with Tutorial Videos & Training
4. Building a checklist


  • React

  • Basiaclly just the View in MVC, to work with remote data, will have to look into additional frameworks like Flux to support your app. But react shares a lot of similarities to other framworks, making future switches easier.
  • Would require a router component
  • can easily use React.js within Aurelia
  • good for performance

can inline html through JSX transpiling e.g....  

render: function() {
return (
<div className = "commentBox"> <h1>Comments</h1>
<CommentList comments = {this.state.data}/>
<CommentForm onCommentSubmit = {this.handleCommentSubmit}/>
<div>


React can render views on the server

  • will start with an intitial state to define immutable state of the component... 
var CommentBox = React.createClass({
get initialState:function(){
return({data:[] });       },   
  • Then public methods like handling compnenet life cycle events:
    • componentDidMount: function() {
    • this.loadCommentsFromServer();
    • setInterval(this.loadCommentsFromServer.bind(this), this.props.pollInterval); }, 
  • Or handling interactions like comment submission:
    • handleCommentSubmit: function (comment){
    • var self = this;
    • this.setState({ data: this.state.data.concat ( comment)}); 

Philosopy to always parsing markup, always rendering.. but compenent lifecypcle methods can combat this expensive "always" rendering act.

get your data from the view, check to see if it's been filled out - pass it back up to the form and then reset the view.

both can pole for data at set intervals, but web sockets would be less network intensive

How react is "changing the game"
  • - Instead of MVC and data binding, a front-end system should have a one-way data flow. Your views should never change the models directly, they always read from the models though, and for writing, they trigger actions that get eventually dispatched to the models (The models are referred to as Stores in this flow). React fits perfectly in the way it "reacts" to data changes in the stores (since it's always listening to that), and re-render the views efficiently (thanks to the Virtual DOM)
  • - Instead of REST, and having the logic of what data to expose on the server-side, then managing different end-points for different needs (for example, one end-point to expose top posts, one to expose a post, and one to expose a post with comments included), let the client asks exactly what they want (using a graph), have the server parses that, and respond with exactly what the client needs (no over-fetching or under-fetching). GraphQL is a great fit for that graph with which the client can ask the server.
  • - Instead of the standard recommended separation of data and views, and since only the view knows exactly which data elements they need to render, don't separate these 2 at all, and have the data requirement expressed in the view component itself, there are huge benefits to this. RelayJS is written to take care of managing this new idea.
--------

  • d3

D3.js (or just D3 for Data-Driven Documents) is a JavaScript library for producing dynamic, interactive data visualizations in web browsers. It makes use of the widely implemented SVG, HTML5, and CSS standards. It is the successor to the earlier Protovis framework.


  • Babylon.js

a 3d game engine based on WebGL and JavaScript for building game that run on browsers. High-quality games complete with physics, audio and particle systems among other things.  A more game oriented alternative to three.js

  • Ember

complete framework 
Seems to be declining.
good with complex nested routes and templates within a page

  • Backbone

toolkit framework - may reply on other tools             
Good for building own framework, defininng own template or using jQuery-like event binding.
But has a steep learning curve and is for advanced developers

  • Knockout

toolkit framework - may reply on other tools

has all basic view rendering features needed for  smallscale app. Good iuf you have to develop your own framework
Expert in data-bindings, easy to setup and work on. 
VIEW> 2 way binding > VIEW MODEL < JS Remoting < MODEL

  • Others

Polymer -
Ionic - 

Can - New, so lacks popularity and support. Easy to use and flexible

----------------------------------------------------------

Mocha& Chai for testing

Mocha is a JavaScript test framework that makes it easy to test the async code in your node module or browser app. Mocha tests can run in series and have the added quality of tracing exceptions to the correct test cases.
Chai is a behavior-driven development/test-driven development assertion library that can be paired with Mocha. It makes it simple to express what you are testing in a readable style.

Karma

Having included Mocha and Chai on this list, it would be incomplete not to include a test runner to run these tests or perhaps to setup continuous integration testing. Karma is a tool designed to help automate running your tests against different browsers. It will help you run your Mocha and Chai tests on all the browsers out there.
Not every browser runs on every platform but luckily there are a couple of free tools you can use to test other browsers, take a look at Browser Screenshots. If you are running on OS X and want to test Edge or Internet Explorer, you can use this tool for free.