如何在egret中调用微信API呢,摸索出两种思路,分别是
官方解决方案简单提一下:
新增 platform.ts 文件
在该文件中,定义一个接口Platform,接口定义了各个平台需要实现的接口,如分享,登录等,各平台分别实现一份XXPlatform, 并通过 下面的代码
if (!window.platform) {
window.platform = new XXPlatform();
}
declare let platform: Platform;
declare interface Window {
platform: Platform
}
声明一个Platform的platform, 外部调用platform就不会出现编译错误了。接下来,按照面向接口编程的思想,在接口中声明需要用到的方案,各平台再实现一份(微信的platform会在打包到微信的时候自动生成)。
自己实现一套跨平台方案,工作量稍大,但是自由度更高,开发流程舒服,直接打包就行,不用担心文件拷贝的问题(laya是适配器的思路)。
跨平台的基本思路是差不多的,抽象行为,面向接口编程。
下面来谈谈几个关键的点
egret.Capabilities.runtimeType
,可以区分部分平台: /**
* 指示当前的运行类型。runtimeType 属性返回下列字符串:
*
* - 运行在Web上 egret.RuntimeType.WEB
* - 运行在Runtime2.0上 egret.RuntimeType.RUNTIME2
* - 运行在微信小游戏上 egret.RuntimeType.WXGAME
*
* @version Egret 2.4
* @platform Web,Native
* @language zh_CN
*/
static readonly runtimeType: string;
let config
try {
config = require('./config')
} catch (e) {
config = require('./config.dev')
}
/**
* 获取 SDK 配置信息
* @return {Object}
*/
const getConfig = () => {
return config
}
// 获取SDK类型
const getAppType = () => {
const config = getConfig()
let type
// h5
if (typeof wx !== 'undefined') {
// 小程序
type = 'wx'
} else if (typeof window !== 'undefined') {
type = 'h5'
} else if (config.type === 3) {
// 快应用功能
type = 'hap'
} else if (process === global.process) {
// 快应用功能
type = 'nodejs'
} else {
// 默认H5
type = 'h5'
}
return type
}
module.exports = { getConfig, getAppType }
思路是将微信小游戏API当作第三方库对待,具体可见文档: 第三方库的使用方法
已经有人写过微信小游戏的.d.ts描述文件了:https://github.com/ETRick/wxOpenDataContext/tree/master/share
放到项目中,将微信小游戏库当作第三方库使用就可以了。(egret官方也整理了一份https://github.com/egret-labs/egret-target-wxgame/tree/master/src)
实现一个Platform_wx类,在该类中调用以上提及的描述文件中声明的方法即,打包成微信即可调用微信接口了。
下面展示一个跨平台的弹窗示例,对于游戏逻辑来说,无需关心平台,只需要调用platform.showModal即可: