本文將介紹開發微信小遊戲四種常用功能的實現方法,這四種功能分別是:
**獲取頭像功能
微信轉發功能
微信分享功能
遊戲圈**
在Egret Wing和微信開發者工具裏的配置
爲實現以上四個功能,我們需要分別在Egret Wing(圖1,圖2)和微信開發者工具(圖3)裏配置。
- 需要在Platform.ts裏調用platform.js接口。
- 在Main.ts通過Platform.ts調用執行函數 。
- 在 platform.js寫相對應的邏輯代碼。
以上三點是實現四個微信小遊戲功能的通用配置,具體操作如下:
獲取頭像
用戶登錄,可以獲取用戶自己的頭像,參看微信平臺。
Egret Wing,已經在Platform.ts寫了默認功能,微信開發者工具已經寫了默認邏輯,開發者只需要在Main添加代碼 在Egret Wing—>src—>Main.ts添加以下代碼
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);
}
微信小遊戲轉發功能
微信小遊戲轉發功能通過點擊微信小遊戲右上角按鈕來觸發小遊戲的內置轉發效果,達到轉發給朋友的效果。
- 在Egret Wing—>src—>Platform.ts添加以下代碼
declare interface Platform {
shop():Promise<any>;
}
class DebugPlatform implements Platform {
async shop() {}
}
- 在Egret Wing—>src—>Main.ts添加以下代碼
private async runGame() {
platform.shop();
}
- 在微信開發者工具裏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();
}
微信小遊戲分享功能
除了轉發功能,我們也可以在微信小遊戲內自定義一個按鈕,主動分享給朋友。
- 在Egret Wing—>src—>Platform.ts添加以下代碼
declare interface Platform {
shareAppMessage():Promise<any>;
}
class DebugPlatform implements Platform {
async shareAppMessage(){}
}
- 在Egret wing—>src—>Main.ts添加以下代碼
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)
}
- 在微信開發者工具裏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(){}
}
- 在Egret Wing—>src—>Main.ts添加以下代碼
private async runGame() {
platform.createGameClubButton();
}
- 在微信開發者工具裏platform.js添加以下代碼
使用方法createGameClubButton().查看參看微信平臺
class WxgamePlatform {
wx.createGameClubButton({
icon: 'green',
style: {
left: 200,
top: 626,
width: 40,
height: 40
}
})
openDataContext = new WxgameOpenDataContext();
以上是微信小遊戲四種常見功能的實現方法,希望對您有所幫助。