CocosCreator项目实战(13):功能-排行榜

本文详细介绍如何使用CocosCreator和微信小游戏API实现排行榜功能,包括主域与子域设置、用户授权流程、分数上传与排行榜展示。


  1. 参考Cocos接入微信小游戏官方文档,为了保护其社交关系链数据,微信小游戏增加了开放数据域的概念。只有在开放数据域中才能访问微信提供的wx.getFriendCloudStorage()wx.getGroupCloudStorage()两个 API来实现排行榜功能。
  2. 查看微信开放接口API的官方文档,了解相关用法。
  3. 参考《Cocos Creator游戏实战》实现微信小游戏排行榜 进行排行榜功能开发。

一、主域设置

  1. box节点下创建rankBox节点,包含rankBgtitleBoxmainBoxbuttonBox。并设置其不可见。
    rankBg:颜色为#FFFFFF78半透明白色,考虑到屏幕适配的情况,添加Widget组件,分别为-30% -27% -35% -35%
    titleBox:包含titleBgtitleLabel,即排行榜文字标签;
    mainBox:包含mainBgopenData,openData为开放数据域;
    buttonBox:包含returnButtonshareButton

在这里插入图片描述

  1. openData节点下添加其他组件 -> WXSubContextView组件

在这里插入图片描述

  1. game.js进行相关函数的增加。首先在属性中添加rankBoxrankButton。并与Canvas节点绑定。
    properties: {
   
   
		...
        rankBox: cc.Node,
        rankButton: cc.Button,
    },
  1. onLoad()方法中,添加对rankButton的click响应事件,调用showRanks方法。并添加initUserInfoButton()方法。
    onLoad() {
   
   
    	...
        this.initUserInfoButton();
        this.rankButton.node.on('click', this.showRanks, this);
    },
  1. 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
        });
    },
  1. 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
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值