- 参考Cocos接入微信小游戏官方文档,为了保护其社交关系链数据,微信小游戏增加了
开放数据域的概念。只有在开放数据域中才能访问微信提供的wx.getFriendCloudStorage()和wx.getGroupCloudStorage()两个 API来实现排行榜功能。
- 查看微信开放接口API的官方文档,了解相关用法。
- 参考《Cocos Creator游戏实战》实现微信小游戏排行榜 进行排行榜功能开发。
一、主域设置
- 在
box节点下创建rankBox节点,包含rankBg、titleBox、mainBox、buttonBox。并设置其不可见。
rankBg:颜色为#FFFFFF78半透明白色,考虑到屏幕适配的情况,添加Widget组件,分别为-30% -27% -35% -35%;
titleBox:包含titleBg、titleLabel,即排行榜文字标签;
mainBox:包含mainBg、openData,openData为开放数据域;
buttonBox:包含returnButton、shareButton。

- 在
openData节点下添加其他组件 -> WXSubContextView组件。

- 对
game.js进行相关函数的增加。首先在属性中添加rankBox、rankButton。并与Canvas节点绑定。
properties: {
...
rankBox: cc.Node,
rankButton: cc.Button,
},
- 在
onLoad()方法中,添加对rankButton的click响应事件,调用showRanks方法。并添加initUserInfoButton()方法。
onLoad() {
...
this.initUserInfoButton();
this.rankButton.node.on('click', this.showRanks, this);
},
showRanks()方法,将rankBox显示可见,并调用wx.getOpenDataContext().postMessage()方法发送score(这里先取了100以内随机数),与子域进行通信生成排行榜内容。
showRanks() {
if (typeof wx === 'undefined') {
return;
}
this.rankBox.active = true;
let score = Math.round(Math.random() * 100);
wx.getOpenDataContext().postMessage({
message: score
});
},
initUserInfoButton()方法为官方文档中微信小游戏用户授权相关。
initUserInfoButton() {
if (typeof wx === 'undefined') {
return;
}
let systemInfo = wx.getSystemInfoSync();
let width = systemInfo.windowWidth;
let height = systemInfo.windowHeight;
let button = wx.createUserInfoButton({
type: 'text',
text: '',
style: {
left: 0,
top: 0,
width: width,
height: height,
lineHeight: 40,
backgroundColor: '#00000000',
color: '#00000000',
textAlign: 'center',
fontSize: 10,
borderRadius: 4
}
});
button.onTap((res) => {
if (res.userInfo) {
console.log('authorized success!');
}
else {
console.log('aut