2014年12月27日 星期六

Nodejs實作(1) - 新手看Nodejs順便動手做!

因為Nodejs實在是太潮了,不學一下實在跟不上時代,因此便開始摸索。


Nodejs


基本與歷史

第一個版本由Ryan Dahl於2009年釋出,後來,Joyent僱用了Dahl,並協助發展Node.js是一個事件驅動I/O伺服器端的Javascript,基於Google V8 engine,本身是一個Server-side的Javascript,來做個比喻也就是PHP與Apache的結合,但Nodejs不需要伺服器。

2014年10月29日 星期三

利用 CORS 解決前端存取 Cross Domain 問題

    今天所要提及的 CORS 全名為 Cross Origin resource sharing,如其字面的意思跨域資源共享,而會接觸到機制是因為前一陣子在存取國內地理資訊機構所提供的 Web Sevice 時,因網站想以 AJAX 方式來呈現資料,故以 JavaScript 這個前端語言來 request 前述的服務,但馬上出了 Acess-Control-Allow-Origin 的問題 。

2014年9月1日 星期一

AngularJS 學習筆記(一) - 概括與基本特色實做

有感於各種Framework的興起,而選定了一個具 MVC 概念的前端JS框架來學習,希望搭配其HTML擴充標籤(各種  ng- 屬性)的特性,還有其雙向資料鏈結(Two ways data-binding),來加速網站開發且讓HTML與JS邏輯透過其MVC架構來分割乾淨。

  • AngularJS 框架定義與運作

From angularjs.org

2014年8月28日 星期四

Unity 存取其他 Component 與存取不同 Object 方法

因為這陣子專案正邁向整合階段,固有許多不同Script或不同Object需要互相存取的需求產生,其實在Unity裡,要達成上述並不難,首先我們先釐清一些觀念:Component 是附加在 GameObject上,故Component可以為腳本或一些效果如Renderer,Collider,Animation等,所以同個GameObject可能會有許多Components!然後我們就可以來簡單嘗試一下如何調用囉!

2014年8月26日 星期二

輕鬆了解 Web Service 的基本概念與運作架構

引言


現在電腦科技日新月異,在我們周遭有許多不同的設備如桌機、筆電、Pad、Smart Phone等,而作業系統也相當多種Windows、IOS、Android等不勝枚舉。

讓我們來假設一個情境,當我正在開發一款 IOS APP 但確是用MS SQL來儲存我們Data,是否就代表著無法運行呢?答案是否定的,而這就是 Web Service 所蘊孕而生的理由,目的在於跨平台交換資料!

Unity 利用 WWW 類別結合 PHP、MySQL 實現 LBS

在上一篇文章 - Unity 運用 LocationService Interface 實現定位功能 後,我們可以來思考如何運用目前所在的地理資訊來得到儲存在DataBase裡離你最近的Data (前提是這些Data也須具有Spatial Type才能進行計算,DataBase Table建置可參考我這篇 - MySQL使用Spatial point type計算點與點間的距離),接下來我們以PHP、MySQL做為後端,以JSON為交換格式,來實現Location Base Service吧!

  • PHP部分 (nearStore.php)
可以發現我們用$_GET來取得 Unity WWW Class 所傳遞過來的資料,而這邊geoPoint就是Unity Client端目前的lacation Data,而最後再將Query出來的結果encode成Json字串格式回傳給客戶端。
header('Content-Type: text/html; charset=utf-8');
    $database = mysql_connect('DB_IP', 'DB_ACCOUNT', 'DB_PassWord') or die('Could not connect: ' . mysql_error());
 mysql_query("SET NAMES 'UTF8'");
    mysql_select_db('openfire_scores') or die('Could not select database');
 
 $geoPoint = mysql_real_escape_string($_GET['geoPoint'], $database); 
 $query = "SELECT *,(GLength(LineStringFromWKB(LineString(geoPoint,GeomFromText('POINT({$geoPoint})'))))) AS distance FROM stores ORDER BY distance ASC LIMIT 5";
 
    $result = mysql_query($query) or die('Query failed: ' . mysql_error());
 
    $num_results = mysql_num_rows($result);  
 
    for($i = 0; $i < $num_results; $i++)
    {
         $row = mysql_fetch_array($result);
         $store_json[$i]["id"] = $row['s_id'];
   $store_json[$i]["name"] = $row['s_name'];
   $store_json[$i]["photoLink"] = $row['s_photoLink'];
   $store_json[$i]["description"] = $row['s_description'];
    }
 
 $echo_json = json_encode($store_json);
 echo $echo_json;
 exit();
  • C#部分 (HSController.cs)
Unity部分主要運用到幾個概念,StartCoroutine等待另一個Function完成、LacationService定位、WWW GET&retrieve PHP的echo Content,Using MiniJson來將PHP回傳的Json decoding 成字串存入陣列!程式邏輯如下:Start() -> GetStore() 嘗試發出Query但要先等待GetGps()得到geoPoint -> 完成後再回到GetStore -> 以GET方式將geoPoint Send往PHP來達成以目前為中心進行 LBS Query -> PHP回傳的JSON字串存在 www.text 再用MiniJson deCoding即可
using UnityEngine;
using System.Collections;
using System.Timers;
using System.Collections.Generic;
using MiniJSON;

public class HSController : MonoBehaviour
{
 public string findStoreURL = "http://your_ip/sample_test/nearStore.php";

 LocationInfo currentGPSPosition;
 public string gps_String;

 void Start()
 {
  StartCoroutine(GetStores());
 }
 
 IEnumerator GetStores()
 {
  string id ="";
  string name ="";
  string url ="";
  string desc ="";
  yield return StartCoroutine (GetGps());//wait for gps
  string findstore_url = findStoreURL + "?geoPoint=" + gps_String;
  print (findstore_url);
  WWW hs_get = new WWW(findstore_url);
  yield return hs_get;
  
  if (hs_get.error != null)
  {
   print("There was an error getting the nearest stores: " + hs_get.error);
  }
  else
  {
   IList jsonList = (IList)Json.Deserialize(hs_get.text);
   
   foreach(IDictionary param in jsonList){
    id = (string)param["id"];
    name = (string)param["name"];
    url = (string)param["photoLink"];
    desc = (string)param["description"];
    Debug.Log("id:"+id);
    Debug.Log("name:"+name);
    Debug.Log("url:"+url);
    Debug.Log("desc:"+desc);
   }
  }
 }

 IEnumerator GetGps()
 {
  if (!Input.location.isEnabledByUser)
   yield break;
  
  Input.location.Start ();
  int maxWait = 20;
  while (Input.location.status == LocationServiceStatus.Initializing && maxWait>0) {
   yield return new WaitForSeconds(1);
   maxWait--;
  }//end while
  if (maxWait < 1) {
   print ("Time out");
   yield break;
  }
  if (Input.location.status == LocationServiceStatus.Failed) {
   print("Unable to determine device location");
   yield break;
  } else {
   print("Location: " + Input.location.lastData.latitude + " " + Input.location.lastData.longitude + " " + Input.location.lastData.altitude + " " + Input.location.lastData.horizontalAccuracy + " " + Input.location.lastData.timestamp);
   currentGPSPosition = Input.location.lastData;
   gps_String = currentGPSPosition.longitude + "%20" + currentGPSPosition.latitude;
   print (gps_String);
   Input.location.Stop();
   yield break;
  }
 } 
}
或許這並不是一個好的解決方式,確是可行的方法,若有其他更好的做法也希望能與我分享討論,最後分享一些參考的連結:

  1. Unity Scripting API - WWW
  2. Unity Scripting API - Couroutine
  3. Unity uses PHP connecting to MySQL -  Server Side Highscores 實現排行板功能

2014年8月25日 星期一

Unity 運用 LocationService Interface 實現定位功能

在Unity裡,也可利用現有的LocationService這個Interface來利用本身載具的定位功能,取得目前所在地的地理資訊(longitude,latitude),接下來也會寫一篇有關Unity實現Location Base Service的方法,所以這篇算是基本的前導。

2014年8月24日 星期日

SQL裡頭的各種JOIN(NATURAL JOIN、OUTER JOIN、INNER JOIN)

Join 這一詞很容易在關連式資料庫運用到,畢竟這是找出TABLE之間,很普遍的用法!
而此篇將參照 Code Project - Visual Representation of SQL Joins 和 資料庫的核心理論與實務 對於JOIN的解釋、運用圖解來進行關念釐清。

多對多的關聯建立與查詢-MySQL為例

在做專案的同時,探討到一個問題,該如何建立多對多的關聯Table並下query查詢呢?
我們想假設一個情況:我正在維護一個系統而裡頭有許多筆玩家的資料皆存在Players這張TABLE,而玩家的目的就是在收集優待券(存在Coupon這張TABLE),而一個玩家會有很多Coupons,相對地同一Coupon也會被許多玩家擁有,那麼該如何建立這種都對多關聯呢?

2014年8月23日 星期六

使用PHP的json_encode&json_decode運用JSON資料格式

    暨寫完上一篇JSON基本知識與Syntax規範後,就立馬用比較熟悉的語言PHP來試試看到底JSON格式是怎麼在PHP裡頭運行,PHP是比較大眾且容易入門的語言,所以常被用來做為Server端語言,當然也有別種像是node.js、ruby、asp等很多都有支持json做為資料交換的格式,詳細可參考 json.org,最後本篇主要使用PHP裡頭的json_encodejson_decode來示範 (PHP 5.2以上版本應有內建)。

2014年8月22日 星期五

JSON基本知識與Syntax規範

基本介紹-

  • 全名為Javascript Object Notation
  • JSON是一個專為儲存交換資料設計的語法
  • JSON比起XML更好使用

MySQL使用Spatial point type計算點與點間的距離

因為目前專案需要做有關LBS的運用,故尋找了一下Mysql儲存地理資訊(Location Based Data)的資料型態與函式,方法如下: 假使有一張Table稱spatialTable,有兩個資料欄位分別為placeName、geoPoint。