Cocos Creator 允許你將代碼拆分成多個腳本文件,並且讓它們相互調用。要實現這點,你需要了解如何在 Cocos Creator 中定義和使用模塊,這個步驟簡稱爲模塊化。
如果你還不確定模塊化究竟能做什麼,模塊化相當於:
- Java 和 Python 中的 import
- C# 中的 using
- C/C++ 中的 include
- HTML 中的
模塊化使你可以在 Cocos Creator 中引用其它腳本文件:
- 訪問其它文件導出的參數
- 調用其它文件導出的方法
- 使用其它文件導出的類型
- 使用或繼承其它 Component
Cocos Creator 中的 JavaScript 使用和 Node.js 幾乎相同的 CommonJS 標準來實現模塊化,簡單來說:
- 每一個單獨的腳本文件就構成一個模塊
- 每個模塊都是一個單獨的作用域
- 以同步的 require 方法來引用其它模塊
- 設置 module.exports 爲導出的變量
引用模塊
require
除了 Creator 提供的接口,所有用戶定義的模塊都需要調用 require 來訪問。例如我們有一個組件定義在 Rotate.js:
// Rotate.js
cc.Class({
extends: cc.Component,
// ...
});
現在要在別的腳本里訪問它,可以:
var Rotate = require(“Rotate”);
require 返回的就是被模塊導出的對象,通常我們都會將結果立即存到一個變量(var Rotate)。傳入 require 的字符串就是模塊的文件名,這個名字不包含路徑也不包含後綴,而且大小寫敏感。
require 完整範例
接着我們就可以使用 Rotate 派生一個子類,新建一個腳本 SinRotate.js:
// SinRotate.js
var Rotate = require("Rotate");
var SinRotate = cc.Class({
extends: Rotate,
update: function (dt) {
this.rotation += this.speed * Math.sin(dt);
}
});
這裏我們定義了一個新的組件叫 SinRotate,它繼承自 Rotate,並對 update 方法進行了重寫。
定義模塊
定義組件
每一個單獨的腳本文件就是一個模塊,例如前面新建的腳本 Rotate.js:
// Rotate.js
var Rotate = cc.Class({
extends: cc.Component,
properties: {
speed: 1
},
update: function () {
this.transform.rotation += this.speed;
}
});
當你在腳本中聲明瞭一個組件,Creator 會默認把它導出,其它腳本直接 require 這個模塊就能使用這個組件。
定義普通 JavaScript 模塊
模塊裏不單單能定義組件,實際上你可以導出任意 JavaScript 對象。假設有個腳本 config.js
// config.js
var cfg = {
moveSpeed: 10,
version: "0.15",
showTutorial: true,
load: function () {
// ...
}
};
cfg.load();
現在如果我們要在其它腳本中訪問 cfg 對象:
// player.js
var config = require("config");
cc.log("speed is", config.moveSpeed);
結果會有報錯:“TypeError: Cannot read property ‘moveSpeed’ of null”,這是因爲 cfg 沒有被導出。由於 require 實際上獲取的是目標腳本內的 module.exports 變量,所以我們還需要在 config.js 的最後設置 module.exports = config:
// config.js - v2
var cfg = {
moveSpeed: 10,
version: "0.15",
showTutorial: true,
load: function () {
// ...
}
};
cfg.load();
module.exports = cfg;
這樣 player.js 便能正確輸出:“speed is 10”。