script.js 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424
  1. // 全局缩放控制
  2. var currentScale = 1;
  3. var baseWidth = 360; // 基准设计宽度
  4. var baseHeight = 640; // 基准设计高度
  5. var buildConfig = null;
  6. // 加载配置文件
  7. async function loadBuildConfig() {
  8. try {
  9. const response = await fetch('https://cdn.goufuguiwxw.com/ResWebGlTest/gfg/config.json');
  10. buildConfig = await response.json();
  11. console.log('配置文件加载成功:', buildConfig);
  12. return buildConfig;
  13. } catch (error) {
  14. console.error('配置文件加载失败:', error);
  15. // 使用默认配置
  16. buildConfig = {
  17. compressionType: "Brotil",
  18. buildPath: "Build/",
  19. compressionConfigs: {
  20. "Brotil": {
  21. dataFile: "webgl.data.br",
  22. frameworkFile: "webgl.framework.js.br",
  23. wasmFile: "webgl.wasm.br",
  24. loaderFile: "webgl.loader.js",
  25. jpgFile: "webgl.jpg"
  26. }
  27. }
  28. };
  29. return buildConfig;
  30. }
  31. }
  32. // 获取文件URL
  33. function getBuildFileUrl(filename) {
  34. if (!buildConfig) {
  35. return `Build/${filename}`;
  36. }
  37. return `${buildConfig.buildPath}${filename}`;
  38. }
  39. // 获取当前压缩配置
  40. function getCurrentCompressionConfig() {
  41. if (!buildConfig) {
  42. return {
  43. dataFile: "webgl.data.br",
  44. frameworkFile: "webgl.framework.js.br",
  45. wasmFile: "webgl.wasm.br",
  46. loaderFile: "webgl.loader.js",
  47. jpgFile: "webgl.jpg"
  48. };
  49. }
  50. const compressionType = buildConfig.compressionType;
  51. return buildConfig.compressionConfigs[compressionType] ||
  52. buildConfig.compressionConfigs["Brotil"];
  53. }
  54. window.onload = async function () {
  55. // 先加载配置文件
  56. await loadBuildConfig();
  57. var container = document.getElementById("unity-container");
  58. var canvas = document.getElementById("unity-canvas");
  59. function updateCanvasSize() {
  60. var windowWidth = window.innerWidth;
  61. var windowHeight = window.innerHeight;
  62. var gameRatio = baseWidth / baseHeight;
  63. // 立即显示容器(避免闪动)
  64. container.style.opacity = '1';
  65. // 初始强制居中
  66. container.style.left = '0';
  67. container.style.right = '0';
  68. canvas.style.left = '0';
  69. canvas.style.margin = '0 auto';
  70. // PC端特殊处理(高度优先)
  71. if (windowWidth > 768) {
  72. // 按高度计算显示宽度
  73. var displayWidth = windowHeight * gameRatio;
  74. currentScale = windowHeight / baseHeight;
  75. // 更新Canvas物理尺寸(解决模糊)
  76. canvas.style.width = displayWidth + 'px';
  77. canvas.style.height = windowHeight + 'px';
  78. canvas.width = displayWidth * window.devicePixelRatio;
  79. canvas.height = windowHeight * window.devicePixelRatio;
  80. }
  81. // 移动端处理
  82. else {
  83. // 保持原比例缩放
  84. var scale = Math.min(
  85. windowWidth / baseWidth,
  86. windowHeight / baseHeight
  87. );
  88. currentScale = scale;
  89. // 更新Canvas物理尺寸
  90. var displayWidth = baseWidth * scale;
  91. var displayHeight = baseHeight * scale;
  92. canvas.style.width = displayWidth + 'px';
  93. canvas.style.height = displayHeight + 'px';
  94. canvas.width = displayWidth * window.devicePixelRatio;
  95. canvas.height = displayHeight * window.devicePixelRatio;
  96. }
  97. // 强制重绘(解决某些浏览器渲染问题)
  98. if (window.unityInstance) {
  99. window.unityInstance.Module.requestAnimationFrame(() => { });
  100. }
  101. }
  102. // 初始化调整
  103. updateCanvasSize();
  104. window.addEventListener('resize', updateCanvasSize);
  105. window.addEventListener('fullscreenchange', updateCanvasSize);
  106. };
  107. // 修复鼠标/触摸事件坐标
  108. function fixEventCoordinates(event) {
  109. if (!window.unityInstance) return;
  110. var rect = canvas.getBoundingClientRect();
  111. var scaleX = canvas.width / rect.width;
  112. var scaleY = canvas.height / rect.height;
  113. // 修正坐标
  114. if (event.clientX !== undefined) {
  115. event.unityX = (event.clientX - rect.left) * scaleX;
  116. event.unityY = (event.clientY - rect.top) * scaleY;
  117. }
  118. }
  119. // 从URL获取SDK参数
  120. function getSDKParamsFromUrl() {
  121. var urlParams = new URLSearchParams(window.location.search);
  122. return {
  123. user_id: urlParams.get('user_id'),
  124. user_name: urlParams.get('user_name'),
  125. uuid: urlParams.get('uuid'),
  126. sign: urlParams.get('sign'),
  127. timestamp: urlParams.get('timestamp'),
  128. cp_ext: urlParams.get('cp_ext')
  129. };
  130. }
  131. // 初始化SDK参数
  132. function initSDKParams() {
  133. sdkParams = getSDKParamsFromUrl();
  134. console.log("SDK Params:", sdkParams);
  135. }
  136. // 显示临时消息横幅
  137. function unityShowBanner(msg, type) {
  138. function updateBannerVisibility() {
  139. warningBanner.style.display = warningBanner.children.length ? 'block' : 'none';
  140. }
  141. var div = document.createElement('div');
  142. div.innerHTML = msg;
  143. warningBanner.appendChild(div);
  144. if (type == 'error') div.style = 'background: red; padding: 10px;';
  145. else {
  146. if (type == 'warning') div.style = 'background: yellow; padding: 10px;';
  147. setTimeout(function () {
  148. warningBanner.removeChild(div);
  149. updateBannerVisibility();
  150. }, 5000);
  151. }
  152. updateBannerVisibility();
  153. }
  154. // 初始化Unity应用
  155. async function initUnity() {
  156. // 确保配置文件已加载
  157. if (!buildConfig) {
  158. await loadBuildConfig();
  159. }
  160. var container = document.querySelector("#unity-container");
  161. var canvas = document.querySelector("#unity-canvas");
  162. var loadingBar = document.querySelector("#unity-loading-bar");
  163. var progressBarFull = document.querySelector("#unity-progress-bar-full");
  164. var fullscreenButton = document.querySelector("#unity-fullscreen-button");
  165. var warningBanner = document.querySelector("#unity-warning");
  166. // 获取当前压缩配置
  167. const compressionConfig = getCurrentCompressionConfig();
  168. // 构建文件URL
  169. const loaderUrl = getBuildFileUrl(compressionConfig.loaderFile);
  170. const dataUrl = getBuildFileUrl(compressionConfig.dataFile);
  171. const frameworkUrl = getBuildFileUrl(compressionConfig.frameworkFile);
  172. const codeUrl = getBuildFileUrl(compressionConfig.wasmFile);
  173. const jpgUrl = getBuildFileUrl(compressionConfig.jpgFile);
  174. console.log('使用压缩格式:', buildConfig.compressionType);
  175. console.log('文件配置:', {
  176. loaderUrl, dataUrl, frameworkUrl, codeUrl, jpgUrl
  177. });
  178. // 监听所有输入事件
  179. ['mousedown', 'mouseup', 'mousemove', 'touchstart', 'touchend', 'touchmove'].forEach(function (eventName) {
  180. canvas.addEventListener(eventName, fixEventCoordinates, { passive: false });
  181. });
  182. var config = {
  183. dataUrl: dataUrl,
  184. frameworkUrl: frameworkUrl,
  185. codeUrl: codeUrl,
  186. streamingAssetsUrl: "StreamingAssets",
  187. companyName: "gfg",
  188. productName: "万世镜",
  189. productVersion: "1.0",
  190. showBanner: unityShowBanner,
  191. devicePixelRatio: window.devicePixelRatio || 1,
  192. preserveDrawingBuffer: true
  193. };
  194. if (/iPhone|iPad|iPod|Android/i.test(navigator.userAgent)) {
  195. canvas.style.width = '100vw';
  196. canvas.style.height = 'calc(100vw * 16/9)';
  197. setTimeout(() => {
  198. canvas.style.width = '100%';
  199. canvas.style.height = '100%';
  200. }, 100);
  201. } else {
  202. config.devicePixelRatio = 1;
  203. }
  204. canvas.style.background = "url('" + jpgUrl + "') center / cover";
  205. loadingBar.style.display = "block";
  206. var script = document.createElement("script");
  207. script.src = loaderUrl;
  208. script.onload = () => {
  209. createUnityInstance(canvas, config, (progress) => {
  210. progressBarFull.style.width = 100 * progress + "%";
  211. }).then((unityInstance) => {
  212. loadingBar.style.display = "none";
  213. window.unityInstance = unityInstance;
  214. fullscreenButton.onclick = () => {
  215. unityInstance.SetFullscreen(1).then(() => {
  216. setTimeout(() => {
  217. canvas.width = canvas.clientWidth * window.devicePixelRatio;
  218. canvas.height = canvas.clientHeight * window.devicePixelRatio;
  219. if (unityInstance.SendMessage) {
  220. unityInstance.SendMessage('JSBridge', 'OnFullscreenChanged', '1');
  221. }
  222. if (/iPhone|iPad|iPod|Android/i.test(navigator.userAgent)) {
  223. document.getElementById("unity-canvas").style.marginLeft = '0';
  224. }
  225. }, 300);
  226. });
  227. };
  228. initSDKParams();
  229. window.unityInstance = unityInstance;
  230. setupSDKCallbacks(unityInstance);
  231. }).catch((message) => {
  232. alert('Unity加载失败: ' + message);
  233. });
  234. };
  235. document.body.appendChild(script);
  236. }
  237. // SDK交互功能
  238. function onSDKLoaded() {
  239. setupSDKCallbacks(window.unityInstance);
  240. }
  241. // 这部分代码将在Unity加载完成后执行
  242. function setupSDKCallbacks(unityInstance) {
  243. // 支付回调示例
  244. window.JHRecharge = function (params) {
  245. console.log("调用支付:", params);
  246. const sdkParams = {
  247. amount: Number(params.amount), // 确保是 Number 类型
  248. cpProductId: params.cpProductId, // cpProductId → cp_product_id
  249. productName: params.productName, // productName → product_name
  250. notifyUrl: "https://webgltest.goufuguiwxw.com/gfg/recharge/jhganmeh5", // notifyUrl → notify_url
  251. serverId: params.serverId, // serverId → server_id
  252. serverName: params.serverName, // serverName → server_name
  253. roleName: params.roleName, // roleName → role_name
  254. roleId: params.roleId, // roleId → role_id
  255. roleLevel: params.roleLevel, // roleLevel → role_level
  256. vipLevel: params.vipLevel, // vipLevel → vip_level
  257. cpOrderId: params.cpOrderId, // cpOrderId → cp_order_id(关键字段)
  258. balance: params.balance, // 确保是 String 类型(文档要求)
  259. extra: params.extra,
  260. fighting: params.fighting
  261. };
  262. // 这里可以添加支付前的Unity交互逻辑
  263. // 例如通知Unity准备支付
  264. if (unityInstance) {
  265. unityInstance.SendMessage('JHGameSDKGameObject', 'OnRechargeStart', JSON.stringify(params));
  266. }
  267. // 调用SDK支付
  268. JHGameSDK.recharge(sdkParams).then(function (res) {
  269. console.log('支付结果:', res);
  270. // 支付完成后通知Unity
  271. if (unityInstance) {
  272. unityInstance.SendMessage('JHGameSDKGameObject', 'OnRechargeComplete', JSON.stringify(res));
  273. }
  274. }).catch(function (error) {
  275. console.error('支付错误:', error);
  276. if (unityInstance) {
  277. unityInstance.SendMessage('JHGameSDKGameObject', 'OnRechargeError', JSON.stringify(error));
  278. }
  279. });
  280. };
  281. // 创建角色回调
  282. window.JHCreateRole = function (params) {
  283. console.log("创建角色:", params);
  284. if (unityInstance) {
  285. unityInstance.SendMessage('JHGameSDKGameObject', 'OnCreateRoleStart', JSON.stringify(params));
  286. }
  287. JHGameSDK.createRole(params).then(function (res) {
  288. console.log('创建角色结果:', res);
  289. if (unityInstance) {
  290. unityInstance.SendMessage('JHGameSDKGameObject', 'OnCreateRoleComplete', JSON.stringify(res));
  291. }
  292. }).catch(function (error) {
  293. console.error('创建角色错误:', error);
  294. if (unityInstance) {
  295. unityInstance.SendMessage('JHGameSDKGameObject', 'OnCreateRoleError', JSON.stringify(error));
  296. }
  297. });
  298. };
  299. // 角色登录回调
  300. window.JHLoginRole = function (params) {
  301. console.log("角色登录:", params);
  302. if (unityInstance) {
  303. unityInstance.SendMessage('JHGameSDKGameObject', 'OnLoginRoleStart', JSON.stringify(params));
  304. }
  305. JHGameSDK.loginRole(params).then(function (res) {
  306. console.log('角色登录结果:', res);
  307. if (unityInstance) {
  308. unityInstance.SendMessage('JHGameSDKGameObject', 'OnLoginRoleComplete', JSON.stringify(res));
  309. }
  310. }).catch(function (error) {
  311. console.error('角色登录错误:', error);
  312. if (unityInstance) {
  313. unityInstance.SendMessage('JHGameSDKGameObject', 'OnLoginRoleError', JSON.stringify(error));
  314. }
  315. });
  316. };
  317. // 角色升级回调
  318. window.JHUpgradeRole = function (params) {
  319. console.log("角色升级:", params);
  320. if (unityInstance) {
  321. unityInstance.SendMessage('JHGameSDKGameObject', 'OnUpgradeRoleStart', JSON.stringify(params));
  322. }
  323. JHGameSDK.upgradeRole(params).then(function (res) {
  324. console.log('角色升级结果:', res);
  325. if (unityInstance) {
  326. unityInstance.SendMessage('JHGameSDKGameObject', 'OnUpgradeRoleComplete', JSON.stringify(res));
  327. }
  328. }).catch(function (error) {
  329. console.error('角色升级错误:', error);
  330. if (unityInstance) {
  331. unityInstance.SendMessage('JHGameSDKGameObject', 'OnUpgradeRoleError', JSON.stringify(error));
  332. }
  333. });
  334. };
  335. // 顶号回调
  336. window.JHRepeatLogin = function () {
  337. console.log("顶号处理");
  338. if (unityInstance) {
  339. unityInstance.SendMessage('JHGameSDKGameObject', 'OnRepeatLoginStart', '');
  340. }
  341. JHGameSDK.repeatLogin().then(function (res) {
  342. console.log('顶号结果:', res);
  343. if (unityInstance) {
  344. unityInstance.SendMessage('JHGameSDKGameObject', 'OnRepeatLoginComplete', JSON.stringify(res));
  345. }
  346. }).catch(function (error) {
  347. console.error('顶号错误:', error);
  348. if (unityInstance) {
  349. unityInstance.SendMessage('JHGameSDKGameObject', 'OnRepeatLoginError', JSON.stringify(error));
  350. }
  351. });
  352. };
  353. // 备案跳转回调
  354. window.JHCallIcpBeian = function () {
  355. console.log("备案跳转");
  356. if (unityInstance) {
  357. unityInstance.SendMessage('JHGameSDKGameObject', 'OnCallIcpBeianStart', '');
  358. }
  359. JHGameSDK.call({ target: "icpbeian" }).then((res) => {
  360. console.log('备案跳转结果:', res);
  361. if (unityInstance) {
  362. unityInstance.SendMessage('JHGameSDKGameObject', 'OnCallIcpBeianComplete', JSON.stringify(res));
  363. }
  364. }).catch(function (error) {
  365. console.error('备案跳转错误:', error);
  366. if (unityInstance) {
  367. unityInstance.SendMessage('JHGameSDKGameObject', 'OnCallIcpBeianError', JSON.stringify(error));
  368. }
  369. });
  370. };
  371. }
  372. // 初始化应用
  373. document.addEventListener('DOMContentLoaded', function () {
  374. initUnity();
  375. });