| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424 |
- // 全局缩放控制
- var currentScale = 1;
- var baseWidth = 360; // 基准设计宽度
- var baseHeight = 640; // 基准设计高度
- var buildConfig = null;
- // 加载配置文件
- async function loadBuildConfig() {
- try {
- const response = await fetch('https://cdn.goufuguiwxw.com/ResWebGlTest/gfg/config.json');
- buildConfig = await response.json();
- console.log('配置文件加载成功:', buildConfig);
- return buildConfig;
- } catch (error) {
- console.error('配置文件加载失败:', error);
- // 使用默认配置
- buildConfig = {
- compressionType: "Brotil",
- buildPath: "Build/",
- compressionConfigs: {
- "Brotil": {
- dataFile: "webgl.data.br",
- frameworkFile: "webgl.framework.js.br",
- wasmFile: "webgl.wasm.br",
- loaderFile: "webgl.loader.js",
- jpgFile: "webgl.jpg"
- }
- }
- };
- return buildConfig;
- }
- }
- // 获取文件URL
- function getBuildFileUrl(filename) {
- if (!buildConfig) {
- return `Build/${filename}`;
- }
- return `${buildConfig.buildPath}${filename}`;
- }
- // 获取当前压缩配置
- function getCurrentCompressionConfig() {
- if (!buildConfig) {
- return {
- dataFile: "webgl.data.br",
- frameworkFile: "webgl.framework.js.br",
- wasmFile: "webgl.wasm.br",
- loaderFile: "webgl.loader.js",
- jpgFile: "webgl.jpg"
- };
- }
- const compressionType = buildConfig.compressionType;
- return buildConfig.compressionConfigs[compressionType] ||
- buildConfig.compressionConfigs["Brotil"];
- }
- window.onload = async function () {
- // 先加载配置文件
- await loadBuildConfig();
- var container = document.getElementById("unity-container");
- var canvas = document.getElementById("unity-canvas");
- function updateCanvasSize() {
- var windowWidth = window.innerWidth;
- var windowHeight = window.innerHeight;
- var gameRatio = baseWidth / baseHeight;
- // 立即显示容器(避免闪动)
- container.style.opacity = '1';
- // 初始强制居中
- container.style.left = '0';
- container.style.right = '0';
- canvas.style.left = '0';
- canvas.style.margin = '0 auto';
- // PC端特殊处理(高度优先)
- if (windowWidth > 768) {
- // 按高度计算显示宽度
- var displayWidth = windowHeight * gameRatio;
- currentScale = windowHeight / baseHeight;
- // 更新Canvas物理尺寸(解决模糊)
- canvas.style.width = displayWidth + 'px';
- canvas.style.height = windowHeight + 'px';
- canvas.width = displayWidth * window.devicePixelRatio;
- canvas.height = windowHeight * window.devicePixelRatio;
- }
- // 移动端处理
- else {
- // 保持原比例缩放
- var scale = Math.min(
- windowWidth / baseWidth,
- windowHeight / baseHeight
- );
- currentScale = scale;
- // 更新Canvas物理尺寸
- var displayWidth = baseWidth * scale;
- var displayHeight = baseHeight * scale;
- canvas.style.width = displayWidth + 'px';
- canvas.style.height = displayHeight + 'px';
- canvas.width = displayWidth * window.devicePixelRatio;
- canvas.height = displayHeight * window.devicePixelRatio;
- }
- // 强制重绘(解决某些浏览器渲染问题)
- if (window.unityInstance) {
- window.unityInstance.Module.requestAnimationFrame(() => { });
- }
- }
- // 初始化调整
- updateCanvasSize();
- window.addEventListener('resize', updateCanvasSize);
- window.addEventListener('fullscreenchange', updateCanvasSize);
- };
- // 修复鼠标/触摸事件坐标
- function fixEventCoordinates(event) {
- if (!window.unityInstance) return;
- var rect = canvas.getBoundingClientRect();
- var scaleX = canvas.width / rect.width;
- var scaleY = canvas.height / rect.height;
- // 修正坐标
- if (event.clientX !== undefined) {
- event.unityX = (event.clientX - rect.left) * scaleX;
- event.unityY = (event.clientY - rect.top) * scaleY;
- }
- }
- // 从URL获取SDK参数
- function getSDKParamsFromUrl() {
- var urlParams = new URLSearchParams(window.location.search);
- return {
- user_id: urlParams.get('user_id'),
- user_name: urlParams.get('user_name'),
- uuid: urlParams.get('uuid'),
- sign: urlParams.get('sign'),
- timestamp: urlParams.get('timestamp'),
- cp_ext: urlParams.get('cp_ext')
- };
- }
- // 初始化SDK参数
- function initSDKParams() {
- sdkParams = getSDKParamsFromUrl();
- console.log("SDK Params:", sdkParams);
- }
- // 显示临时消息横幅
- function unityShowBanner(msg, type) {
- function updateBannerVisibility() {
- warningBanner.style.display = warningBanner.children.length ? 'block' : 'none';
- }
- var div = document.createElement('div');
- div.innerHTML = msg;
- warningBanner.appendChild(div);
- if (type == 'error') div.style = 'background: red; padding: 10px;';
- else {
- if (type == 'warning') div.style = 'background: yellow; padding: 10px;';
- setTimeout(function () {
- warningBanner.removeChild(div);
- updateBannerVisibility();
- }, 5000);
- }
- updateBannerVisibility();
- }
- // 初始化Unity应用
- async function initUnity() {
- // 确保配置文件已加载
- if (!buildConfig) {
- await loadBuildConfig();
- }
- var container = document.querySelector("#unity-container");
- var canvas = document.querySelector("#unity-canvas");
- var loadingBar = document.querySelector("#unity-loading-bar");
- var progressBarFull = document.querySelector("#unity-progress-bar-full");
- var fullscreenButton = document.querySelector("#unity-fullscreen-button");
- var warningBanner = document.querySelector("#unity-warning");
- // 获取当前压缩配置
- const compressionConfig = getCurrentCompressionConfig();
- // 构建文件URL
- const loaderUrl = getBuildFileUrl(compressionConfig.loaderFile);
- const dataUrl = getBuildFileUrl(compressionConfig.dataFile);
- const frameworkUrl = getBuildFileUrl(compressionConfig.frameworkFile);
- const codeUrl = getBuildFileUrl(compressionConfig.wasmFile);
- const jpgUrl = getBuildFileUrl(compressionConfig.jpgFile);
- console.log('使用压缩格式:', buildConfig.compressionType);
- console.log('文件配置:', {
- loaderUrl, dataUrl, frameworkUrl, codeUrl, jpgUrl
- });
- // 监听所有输入事件
- ['mousedown', 'mouseup', 'mousemove', 'touchstart', 'touchend', 'touchmove'].forEach(function (eventName) {
- canvas.addEventListener(eventName, fixEventCoordinates, { passive: false });
- });
- var config = {
- dataUrl: dataUrl,
- frameworkUrl: frameworkUrl,
- codeUrl: codeUrl,
- streamingAssetsUrl: "StreamingAssets",
- companyName: "gfg",
- productName: "万世镜",
- productVersion: "1.0",
- showBanner: unityShowBanner,
- devicePixelRatio: window.devicePixelRatio || 1,
- preserveDrawingBuffer: true
- };
- if (/iPhone|iPad|iPod|Android/i.test(navigator.userAgent)) {
- canvas.style.width = '100vw';
- canvas.style.height = 'calc(100vw * 16/9)';
- setTimeout(() => {
- canvas.style.width = '100%';
- canvas.style.height = '100%';
- }, 100);
- } else {
- config.devicePixelRatio = 1;
- }
- canvas.style.background = "url('" + jpgUrl + "') center / cover";
- loadingBar.style.display = "block";
- var script = document.createElement("script");
- script.src = loaderUrl;
- script.onload = () => {
- createUnityInstance(canvas, config, (progress) => {
- progressBarFull.style.width = 100 * progress + "%";
- }).then((unityInstance) => {
- loadingBar.style.display = "none";
- window.unityInstance = unityInstance;
- fullscreenButton.onclick = () => {
- unityInstance.SetFullscreen(1).then(() => {
- setTimeout(() => {
- canvas.width = canvas.clientWidth * window.devicePixelRatio;
- canvas.height = canvas.clientHeight * window.devicePixelRatio;
- if (unityInstance.SendMessage) {
- unityInstance.SendMessage('JSBridge', 'OnFullscreenChanged', '1');
- }
- if (/iPhone|iPad|iPod|Android/i.test(navigator.userAgent)) {
- document.getElementById("unity-canvas").style.marginLeft = '0';
- }
- }, 300);
- });
- };
- initSDKParams();
- window.unityInstance = unityInstance;
- setupSDKCallbacks(unityInstance);
- }).catch((message) => {
- alert('Unity加载失败: ' + message);
- });
- };
- document.body.appendChild(script);
- }
- // SDK交互功能
- function onSDKLoaded() {
- setupSDKCallbacks(window.unityInstance);
- }
- // 这部分代码将在Unity加载完成后执行
- function setupSDKCallbacks(unityInstance) {
- // 支付回调示例
- window.JHRecharge = function (params) {
- console.log("调用支付:", params);
- const sdkParams = {
- amount: Number(params.amount), // 确保是 Number 类型
- cpProductId: params.cpProductId, // cpProductId → cp_product_id
- productName: params.productName, // productName → product_name
- notifyUrl: "https://webgltest.goufuguiwxw.com/gfg/recharge/jhganmeh5", // notifyUrl → notify_url
- serverId: params.serverId, // serverId → server_id
- serverName: params.serverName, // serverName → server_name
- roleName: params.roleName, // roleName → role_name
- roleId: params.roleId, // roleId → role_id
- roleLevel: params.roleLevel, // roleLevel → role_level
- vipLevel: params.vipLevel, // vipLevel → vip_level
- cpOrderId: params.cpOrderId, // cpOrderId → cp_order_id(关键字段)
- balance: params.balance, // 确保是 String 类型(文档要求)
- extra: params.extra,
- fighting: params.fighting
- };
- // 这里可以添加支付前的Unity交互逻辑
- // 例如通知Unity准备支付
- if (unityInstance) {
- unityInstance.SendMessage('JHGameSDKGameObject', 'OnRechargeStart', JSON.stringify(params));
- }
- // 调用SDK支付
- JHGameSDK.recharge(sdkParams).then(function (res) {
- console.log('支付结果:', res);
- // 支付完成后通知Unity
- if (unityInstance) {
- unityInstance.SendMessage('JHGameSDKGameObject', 'OnRechargeComplete', JSON.stringify(res));
- }
- }).catch(function (error) {
- console.error('支付错误:', error);
- if (unityInstance) {
- unityInstance.SendMessage('JHGameSDKGameObject', 'OnRechargeError', JSON.stringify(error));
- }
- });
- };
- // 创建角色回调
- window.JHCreateRole = function (params) {
- console.log("创建角色:", params);
- if (unityInstance) {
- unityInstance.SendMessage('JHGameSDKGameObject', 'OnCreateRoleStart', JSON.stringify(params));
- }
- JHGameSDK.createRole(params).then(function (res) {
- console.log('创建角色结果:', res);
- if (unityInstance) {
- unityInstance.SendMessage('JHGameSDKGameObject', 'OnCreateRoleComplete', JSON.stringify(res));
- }
- }).catch(function (error) {
- console.error('创建角色错误:', error);
- if (unityInstance) {
- unityInstance.SendMessage('JHGameSDKGameObject', 'OnCreateRoleError', JSON.stringify(error));
- }
- });
- };
- // 角色登录回调
- window.JHLoginRole = function (params) {
- console.log("角色登录:", params);
- if (unityInstance) {
- unityInstance.SendMessage('JHGameSDKGameObject', 'OnLoginRoleStart', JSON.stringify(params));
- }
- JHGameSDK.loginRole(params).then(function (res) {
- console.log('角色登录结果:', res);
- if (unityInstance) {
- unityInstance.SendMessage('JHGameSDKGameObject', 'OnLoginRoleComplete', JSON.stringify(res));
- }
- }).catch(function (error) {
- console.error('角色登录错误:', error);
- if (unityInstance) {
- unityInstance.SendMessage('JHGameSDKGameObject', 'OnLoginRoleError', JSON.stringify(error));
- }
- });
- };
- // 角色升级回调
- window.JHUpgradeRole = function (params) {
- console.log("角色升级:", params);
- if (unityInstance) {
- unityInstance.SendMessage('JHGameSDKGameObject', 'OnUpgradeRoleStart', JSON.stringify(params));
- }
- JHGameSDK.upgradeRole(params).then(function (res) {
- console.log('角色升级结果:', res);
- if (unityInstance) {
- unityInstance.SendMessage('JHGameSDKGameObject', 'OnUpgradeRoleComplete', JSON.stringify(res));
- }
- }).catch(function (error) {
- console.error('角色升级错误:', error);
- if (unityInstance) {
- unityInstance.SendMessage('JHGameSDKGameObject', 'OnUpgradeRoleError', JSON.stringify(error));
- }
- });
- };
- // 顶号回调
- window.JHRepeatLogin = function () {
- console.log("顶号处理");
- if (unityInstance) {
- unityInstance.SendMessage('JHGameSDKGameObject', 'OnRepeatLoginStart', '');
- }
- JHGameSDK.repeatLogin().then(function (res) {
- console.log('顶号结果:', res);
- if (unityInstance) {
- unityInstance.SendMessage('JHGameSDKGameObject', 'OnRepeatLoginComplete', JSON.stringify(res));
- }
- }).catch(function (error) {
- console.error('顶号错误:', error);
- if (unityInstance) {
- unityInstance.SendMessage('JHGameSDKGameObject', 'OnRepeatLoginError', JSON.stringify(error));
- }
- });
- };
- // 备案跳转回调
- window.JHCallIcpBeian = function () {
- console.log("备案跳转");
- if (unityInstance) {
- unityInstance.SendMessage('JHGameSDKGameObject', 'OnCallIcpBeianStart', '');
- }
- JHGameSDK.call({ target: "icpbeian" }).then((res) => {
- console.log('备案跳转结果:', res);
- if (unityInstance) {
- unityInstance.SendMessage('JHGameSDKGameObject', 'OnCallIcpBeianComplete', JSON.stringify(res));
- }
- }).catch(function (error) {
- console.error('备案跳转错误:', error);
- if (unityInstance) {
- unityInstance.SendMessage('JHGameSDKGameObject', 'OnCallIcpBeianError', JSON.stringify(error));
- }
- });
- };
- }
- // 初始化应用
- document.addEventListener('DOMContentLoaded', function () {
- initUnity();
- });
|