Firebase Functionsをゲームサーバーにしてみよう。
Firebase DatabaseとUnityでオンラインゲームを作るとして、 サーバーというか、GlobalManagerロールをどうしようってなったので Firebase Functionsでやってみようと思います。
今回やることは
1分ごとに、 - マップ上にランダムに木を生成する。 - ゲーム内時間を進める。
データ構造
{ "world": { "time": 1, "resources": { "wood": 0 }, "objects": [ { "type": "wood", "position": { "x":0, "y":0, "x":0, } }, { "type": "wood", "position": { "x":2, "y":0, "x":0, } } ] } }
こんな感じかな。 Functionsでobjectsにwoodを入れていく。
プレイヤーは木を切るとresources.woodを+1する。
やっていく
https://console.firebase.google.com まず適当にFirebaseプロジェクトを作る
npm install -g firebase-tools
firebaseのCLIをインストールして、 適当な空のディレクトリに移動してから
$ firebase init functions
生成されたindex.js
の中は
const functions = require('firebase-functions'); const admin = require('firebase-admin'); admin.initializeApp(functions.config().firebase); exports.tick = functions.https.onRequest((request, response) => { admin.database().ref('/world/time').once("value") .then(snapshot => { admin.database().ref('/world/time').set(1 + snapshot.val()); }) admin.database().ref("/world/objects").push({ type: 'tree', position: { x: Math.floor(Math.random() * 51), y: 1, z: Math.floor(Math.random() * 51) } }); response.status(200).end(); });
こんな感じ。
コードの記述が終わったらデプロイをする。
$ firebase deploy --only functions
これでHTTPSのエンドポイントURLが発行される。
定期的に実行する
cron-job.org - Free cronjobs - from minutely to once a year.
これとか使ってみます。 定期的にHTTPリクエストを送ってくれるサービス。 1分毎に叩くように設定してみた。
これで 「1分毎に新たに木が生え、ゲーム内時間が進む」 が実装されました。