Global Variables
Since all plug-in scripts are guaranteed to be loaded before the normal script, then in addition to load plug-ins, you can also use this feature to declare some special global variables. You can add a script in the project, and set the "Import to plug-in":
/ * * Globals.js /
// 定义新建组件的默认值
window.DEFAULT_IP = "192.168.1.1";
// 定义组件开关
window.ENABLE_NET_DEBUGGER = true;
// 定义引擎 API 缩写(仅适用于构造函数)
window.V2 = cc.Vec2;
接下来你就能在任意的普通脚本中直接访问它们:
/* network.js */
cc.Class({
extends: cc.Component,
properties: {
ip: {
default: DEFAULT_IP
}
}
});
/* network_debugger.js */
if (ENABLE_NET_DEBUGGER) {
// ENABLE_NET_DEBUGGER 时这个组件才生效
cc.Class({
extends: cc.Component,
properties: {
location: {
default: new V2(100, 200)
}
},
update: function () {
...
},
});
}
else {
// 否则这个组件什么也不做
cc.Class({
extends: cc.Component,
start: function () {
// 在开始后就移除该组件
this.destroy();
}
});
}
Standard network interface
In Cocos Creator, we support standard network interfaces on the Web platform the most widely used:
XMLHttpRequest: for short connection
WebSocket: for a long connection
, of course, the Web platform, gifted with the original browser supports both interfaces, the reason that Cocos Creator support, because when you publish a native version, users of these two network interfaces the code also can run. That is to follow, "a source, multi-platform" has been adhering to the principle of Cocos.
Instructions
XMLHttpRequest 简单示例:
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function () {
if (xhr.readyState == 4 && (xhr.status >= 200 && xhr.status < 400)) {
var response = xhr.responseText;
console.log(response);
}
};
xhr.open("GET", url, true);
xhr.send();
Developers can directly use the new XMLHttpRequest () to create a connection object, it can also be created by cc.loader.getXMLHttpRequest (), both consistent effect.
Refer to the document standard XMLHttpRequest MDN Chinese documents .
WebSocket
A simple example:
ws = new WebSocket("ws://echo.websocket.org");
ws.onopen = function (event) {
console.log("Send Text WS was opened.");
};
ws.onmessage = function (event) {
console.log("response text msg: " + event.data);
};
ws.onerror = function (event) {
console.log("Send Text fired an error");
};
ws.onclose = function (event) {
console.log("WebSocket instance closed.");
};
setTimeout(function () {
if (ws.readyState === WebSocket.OPEN) {
ws.send("Hello WebSocket, I'm a text message.");
}
else {
console.log("WebSocket instance wasn't ready...");
}
}, 3);
WebSocket standard document, please refer MDN Chinese documents .