本文將介紹開發微信小游戲四種常用功能的實現方法,這四種功能分別是:
-
獲取頭像功能
-
微信轉發功能
-
微信分享功能
-
游戲圈
在Egret Wing和微信開發者工具里的配置
為實現以上四個功能,我們需要分別在Egret Wing(圖1,圖2)和微信開發者工具(圖3)里配置。
-
需要在Platform.ts里調用platform.js接口。
-
在Main.ts通過Platform.ts調用執行函數 。
-
在 platform.js寫相對應的邏輯代碼。
以上三點是實現四個微信小游戲功能的通用配置,具體操作如下:
獲取頭像
用戶登錄,可以獲取用戶自己的頭像,參看微信平台。
private async runGame() { const userInfo = await platform.getUserInfo(); this.createGameScene(userInfo); } protected createGameScene(userInfo:any): void { // 用戶頭像 let img=new eui.Image(); img.source=userInfo.avatarUrl this.addChild(img); }
微信小游戲轉發功能
微信小游戲轉發功能通過點擊微信小游戲右上角按鈕來觸發小游戲的內置轉發效果,達到轉發給朋友的效果。
1. 在Egret Wing—>src—>Platform.ts添加以下代碼
declare interface Platform { shop():Promise<any>; } class DebugPlatform implements Platform { async shop() {} }
private async runGame() { platform.shop(); }
3. 在微信開發者工具里Platform.ts添加以下代碼
微信轉發主要使用了wx.showShareMenu()和wx.onShareAppMessage()方法,具體參數可參看微信開發平台
class WxgamePlatform { shop() { return new Promise((resolve, reject) => { wx.showShareMenu({ withShareTicket: true }); wx.onShareAppMessage(function () { return { title: "+++", imageUrl: 'resource/assets/art/heros_goods/btnOK.png' } }) }) } openDataContext = new WxgameOpenDataContext(); }
微信小游戲分享功能
除了轉發功能,我們也可以在微信小游戲內自定義一個按鈕,主動分享給朋友。
1. 在Egret Wing—>src—>Platform.ts添加以下代碼
declare interface Platform { shareAppMessage():Promise<any>; } class DebugPlatform implements Platform { async shareAppMessage(){} }
protected createGameScene(): void { //游戲內自定義分享按鈕 let btnClose = new eui.Button(); btnClose.label = "分享"; btnClose.y = 300; btnClose.horizontalCenter =180; this.addChild(btnClose); btnClose.addEventListener(egret.TouchEvent.TOUCH_TAP, ()=>{ platform.shareAppMessage() }, this) }
3. 在微信開發者工具里Platform.ts添加以下代碼
微信分享主要使用了shareAppMessage()方法,具體參數可參看微信開發平台
class WxgamePlatform { shareAppMessage() { return new Promise((resolve, reject) => { wx.shareAppMessage({ title: '轉發標題', imageUrl: 'resource/assets/art/heros_goods/btnOK.png' }) }) } openDataContext = new WxgameOpenDataContext(); }
游戲圈
微信游戲圈,在這里和好友交流游戲心得。 1. 在Egret Wing—>src—>Platform.ts添加以下代碼
declare interface Platform { createGameClubButton():Promise<any>; } class DebugPlatform implements Platform { async createGameClubButton(){} }
private async runGame() { platform.createGameClubButton(); }
class WxgamePlatform { wx.createGameClubButton({ icon: 'green', style: { left: 200, top: 626, width: 40, height: 40 } }) openDataContext = new WxgameOpenDataContext(); }
以上是微信小游戲四種常見功能的實現方法,希望對您有所幫助。