湖北Webgl项目开发笔记

问题1:点击“截图记录”时,无法显示出图片?

答:未修改HBPRO-0.0.1-SNAPSHOT(2).jar,位于D:\HBPRO\HBPRO-0.0.1-SNAPSHOT(2).jar

问题2:打包AB包后,加载个别步骤的Timeline的时候,Unity编辑器突然闪退!!

答:这里是由于里面的语音格式导致的,修改后便不会闪退了;

修改前语音格式:

修改后语音格式:

问题3: index.html备份

解决问题(1):Webgl在安卓和苹果设备上需要呈现不同的UI内容、以及手机端需要横屏按钮;

解决问题(2):   点击浏览器上的刷新按钮或关闭按钮后,账户退出登录问题;

解决问题(3):  其他浏览器都是异步退出登录,只有火狐浏览器需要同步方式退出。

解决问题(4):动态调整Windows下 不同分辨率显示器呈现的UI界面;

解决问题(5):安卓后台退出webgl程序进程后,账户无法退出问题;

<!DOCTYPE html>
<html lang="en-us">
  <head>
    <meta charset="utf-8">
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <title>Unity WebGL Player | 配网带电作业数字化实训平台</title>
    <link rel="shortcut icon" href="TemplateData/favicon.ico">
    <link rel="stylesheet" href="TemplateData/style.css">
  </head>
  <body>
      <div id="unity-container" class="unity-desktop">
          <canvas id="unity-canvas" width=1920 height=1080></canvas>
          <div id="unity-loading-bar">
              <div id="unity-logo"></div>
              <div id="unity-progress-bar-empty">
                  <div id="unity-progress-bar-full"></div>
              </div>
          </div>
          <div id="unity-warning"> </div>
          <div id="unity-footer">
              <div id="unity-webgl-logo"></div>
              <div id="unity-fullscreen-button"></div>
              <div id="unity-build-title">配网带电作业数字化实训平台</div>
          </div>
      </div>
      <script>
          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");

          // Shows a temporary message banner/ribbon for a few seconds, or
          // a permanent error message on top of the canvas if type=='error'.
          // If type=='warning', a yellow highlight color is used.
          // Modify or remove this function to customize the visually presented
          // way that non-critical warnings and error messages are presented to the
          // user.
          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();
          }

          var platformName = "";
          var buildUrl = "Build";
          var loaderUrl = buildUrl + "/Test.loader.js";
          var config = {
              dataUrl: buildUrl + "/Test.data.unityweb",
              frameworkUrl: buildUrl + "/Test.framework.js.unityweb",
              codeUrl: buildUrl + "/Test.wasm.unityweb",
              streamingAssetsUrl: "StreamingAssets",
              companyName: "DefaultCompany",
              productName: "配网带电作业数字化实训平台",
              productVersion: "0.1",
              showBanner: unityShowBanner,
          };

          // By default Unity keeps WebGL canvas render target size matched with
          // the DOM size of the canvas element (scaled by window.devicePixelRatio)
          // Set this to false if you want to decouple this synchronization from
          // happening inside the engine, and you would instead like to size up
          // the canvas DOM size and WebGL render target sizes yourself.
          // config.matchWebGLToCanvasSize = false;

          if (/iPhone|iPad|iPod|Android/i.test(navigator.userAgent)) {
              // Mobile device style: fill the whole browser client area with the game canvas:

              if (/Android/i.test(navigator.userAgent)) {
                  platformName = "安卓";
              }
              else if (/iPhone/i.test(navigator.userAgent)) {
                  platformName = "苹果";
              }

              var meta = document.createElement('meta');
              meta.name = 'viewport';
              meta.content = 'width=device-width, height=device-height, initial-scale=1.0, user-scalable=no, shrink-to-fit=yes';
              document.getElementsByTagName('head')[0].appendChild(meta);
              container.className = "unity-mobile";
              canvas.className = "unity-mobile";

              // To lower canvas resolution on mobile devices to gain some
              // performance, uncomment the following line:
              // config.devicePixelRatio = 1;
              canvas.style.width = window.innerWidth + 'px';
              canvas.style.height = window.innerWidth / (1920 / 1080) + 'px';

              unityShowBanner('微信浏览器--请提前打开“自动旋转屏幕”或取消“方向锁定”,然后前往微信通用设置-开启横屏模式。');
          } else {
              // Desktop style: Render the game canvas in a window that can be maximized to fullscreen:
              platformName = "电脑";
              canvas.style.width = window.innerHeight * (1920 / 1080) + 'px';
              canvas.style.height = window.innerHeight + 'px';
          }

          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) => {
                  unityInstance.SendMessage("手机端横屏", "当前平台", platformName);
                  loadingBar.style.display = "none";
                  fullscreenButton.onclick = () => {
                      unityInstance.SetFullscreen(1);
                  };
              }).catch((message) => {
                  alert(message);
              });
          };
          document.body.appendChild(script);
      </script>

      <script type="text/javascript">
          var userName = "";
          function SayGoodBye(way) {
              userName = way;
          }
      </script>

      <script>

          // 监听页面可见性变化(安卓手机后台直接杀掉程序进程,同样判定为账号退出)
          document.addEventListener('visibilitychange', function (e) {
              if (document.hidden) {
                  // 发送 HTTP 请求
                  var xhr = new XMLHttpRequest();
                  //是否为火狐浏览器
                  if (navigator.userAgent.indexOf('Firefox') != -1) {
                      xhr.open('POST', 'http://192.168.1.99:8082/HBPRO/userController/loginOut', false);//同步
                  }
                  else {
                      xhr.open('POST', 'http://192.168.1.99:8082/HBPRO/userController/loginOut', true);//异步
                  }
                  xhr.setRequestHeader('Content-Type', 'application/json');
                  xhr.onreadystatechange = function () {
                      if (xhr.readyState === XMLHttpRequest.DONE) {
                          // 在请求完成后可以执行一些操作
                          console.log('HTTP 请求已发送');
                      }
                  };
                  var obj = { userName: userName }
                  //httpRequest.send(JSON.stringify(obj));//发送请求 将json写入send中
                  xhr.send(JSON.stringify(obj));
              }
          });

          //在浏览器上关闭、刷新网页,判定为账号退出
         window.addEventListener('beforeunload', function (e) {
              // 发送 HTTP 请求
             var xhr = new XMLHttpRequest();
             //是否为火狐浏览器
             if (navigator.userAgent.indexOf('Firefox') != -1) {
                 xhr.open('POST', 'http://192.168.1.99:8082/HBPRO/userController/loginOut', false);//同步
             }
             else
             {
                 xhr.open('POST', 'http://192.168.1.99:8082/HBPRO/userController/loginOut', true);//异步
             }
              xhr.setRequestHeader('Content-Type', 'application/json');
              xhr.onreadystatechange = function () {
                  if (xhr.readyState === XMLHttpRequest.DONE) {
                      // 在请求完成后可以执行一些操作
                      console.log('HTTP 请求已发送');
                  }
              };
              var obj = { userName: userName }
              //httpRequest.send(JSON.stringify(obj));//发送请求 将json写入send中
             xhr.send(JSON.stringify(obj));
          });
      </script>

      <script type="text/javascript">
          function myFunction() {
              // JavaScript code here
              var httpRequest = new XMLHttpRequest();//第一步:建立须要的对象
              httpRequest.open('POST', 'http://192.168.1.99:8082/HBPRO/userController/loginOut', true); //第二步:打开链接/***发送json格式文件必须设置请求头 ;以下 - */
              httpRequest.setRequestHeader("Content-type", "application/json");//设置请求头 注:post方式必须设置请求头(在创建链接后设置请求头)var obj = { name: 'zhansgan', age: 18 };
              //r obj = { userName: 'admin', age: 18 };
              var obj = { userName: userName }
              httpRequest.send(JSON.stringify(obj));//发送请求 将json写入send中
          }
      </script>
  </body>
</html>

问题4:Webgl在windows上鼠标右键控制相机上下左右视角变化,鼠标滚轮拉进拉远相机视角,在安卓苹果移动平台,需要修改为单指控制相机视角变化,双指控制相机拉进拉远?

using UnityEngine;

public class CameraFollow : MonoBehaviour
{
    public static CameraFollow instance;

    public GameObject 相机正在跟随的目标;
    public float xSpeed = 200;  //X轴方向拖动速度
    public float ySpeed = 200;  //Y轴方向拖动速度
    public float mSpeed = 10;   //放大缩小速度
    public float yMinLimit = -50; //在Y轴最小移动范围
    public float yMaxLimit = 50; //在Y轴最大移动范围
    public float distance = 10;  //相机视角距离
    public float minDinstance = 2; //相机视角最小距离
    public float maxDinstance = 30; //相机视角最大距离
    public float angleX = 0.0f;
    public float angleY = 0.0f;
    public float 镜头切换速度 = 5.0f;
    public bool needDamping = true;

    private Vector3 offset;

    void Awake()
    {
        instance = this;
    }

    void Start()
    {
        Vector3 angle = transform.eulerAngles;
        angleX = angle.y;
        angleY = angle.x;
        offset = transform.position - 相机正在跟随的目标.transform.position;
    }

    void LateUpdate() //处理相机部分
    {
        if (GlobalVariableManager.是否暂停相机旋转 == false)
        {
            RotateAndScroll();
            AvoidCrossWall();
        }
    }

    private float ClampAngle(float angle, float min, float max)
    {
        if (angle < -360)
        {
            angle += 360;
        }
        if (angle > 360)
        {
            angle -= 360;
        }
        return Mathf.Clamp(angle, min, max);
    }

    //旋转和放缩
    private void RotateAndScroll()
    {
        单指旋转();
        双指放缩();

        //鼠标右键上下左右旋转
        if (Input.GetMouseButton(1))
        {
            angleX += Input.GetAxis("Mouse X") * xSpeed * 0.02f;
            angleY -= Input.GetAxis("Mouse Y") * ySpeed * 0.02f;
            angleY = ClampAngle(angleY, yMinLimit, yMaxLimit);
        }

        //鼠标滚轮拉进拉远
        distance -= Input.GetAxis("Mouse ScrollWheel") * mSpeed;
        distance = Mathf.Clamp(distance, minDinstance, maxDinstance);
        Quaternion rotation = Quaternion.Euler(angleY, angleX, 0.0f);
        Vector3 disVector = new Vector3(0.0f, 0.0f, -distance);
        Vector3 position = rotation * disVector + 相机正在跟随的目标.transform.position;

        if (needDamping)
        {
            transform.rotation = Quaternion.Lerp(transform.rotation, rotation, Time.deltaTime * 镜头切换速度);
            //if (GlobalVariableManager.cameraFollowTarget.parent.GetComponent<PlayerController>() != null)
            //{
            //    GlobalVariableManager.cameraFollowTarget.parent.rotation = Quaternion.Lerp(GlobalVariableManager.cameraFollowTarget.parent.rotation,
            //        Quaternion.Euler(GlobalVariableManager.cameraFollowTarget.parent.eulerAngles.x, transform.eulerAngles.y, GlobalVariableManager.cameraFollowTarget.parent.eulerAngles.z), Time.deltaTime * damping);//让player始终朝向相机正前方
            //}
            transform.position = Vector3.Lerp(transform.position, position, Time.deltaTime * 镜头切换速度);
        }
        else
        {
            transform.rotation = rotation;
            transform.position = position;
        }
    }

    //防穿墙
    private void AvoidCrossWall()
    {
        RaycastHit hit;
        if (Physics.Raycast(相机正在跟随的目标.transform.position, transform.position - 相机正在跟随的目标.transform.position, out hit, Vector3.Distance(transform.position, 相机正在跟随的目标.transform.position))) ;
        {
            if (hit.collider != null)
            {
                if (hit.collider.tag == "地面防穿墙")
                {
                    transform.position = hit.point;
                }
            }
        }
    }

    //单指上下左右旋转相机
    private void 单指旋转()
    {
        if (Input.touchCount == 1) // 如果有触摸
        {
            Touch touch = Input.GetTouch(0); // 获取第一个触摸

            if (touch.phase == TouchPhase.Moved) // 如果触摸是移动的
            {
                Vector2 deltaPos = touch.deltaPosition; // 获取触摸的位置差
                angleX -= deltaPos.x * 1; // 更新水平旋转角度
                angleY += deltaPos.y * 1;
                angleY = ClampAngle(angleY, yMinLimit, yMaxLimit);
            }
        }
    }

    
    private bool IsZoom = false;//是否缩放
    private float DoubleTouchCurrDis;//当前双指触控间距
    private float DoubleTouchLastDis;//过去双指触控间距

    //双指拉进拉远相机
    private void 双指放缩()
    {
        if ((Input.touchCount > 1) && (Input.GetTouch(0).phase == TouchPhase.Moved || Input.GetTouch(1).phase == TouchPhase.Moved))
        {
            Touch touch1 = Input.GetTouch(0);
            Touch touch2 = Input.GetTouch(1);

            DoubleTouchCurrDis = Vector2.Distance(touch1.position, touch2.position);

            if (!IsZoom)
            {
                DoubleTouchLastDis = DoubleTouchCurrDis;
                IsZoom = true;
            }

            float dis = DoubleTouchCurrDis - DoubleTouchLastDis;
            distance -= dis * 0.1f;
            distance = Mathf.Clamp(distance, minDinstance, maxDinstance);
            DoubleTouchLastDis = DoubleTouchCurrDis;
        }
    }
}

问题5:

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

林枫依依

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值