1198 lines
43 KiB
C#
Raw Normal View History

using Assets.Scripts.Apis;
using Assets.Scripts.Apis.Models;
2021-03-28 18:17:15 +08:00
using System;
using System.Linq;
using System.Collections;
using System.Collections.Generic;
2021-03-29 20:32:30 +08:00
using UnityEngine.Networking;
using Assets.Scenes.Ride.Scripts.Model;
using Assets.Scenes.Ride.Scripts.Model.CyclingModels;
using Assets.Scenes.Ride.Scripts;
using Mapbox.Unity.Map;
using UnityEngine;
using GeoJSON.Net.Geometry;
using TurfCS;
using Mapbox.Utils;
using Assets.Scripts;
2021-04-21 14:08:45 +08:00
using System.Threading.Tasks;
2021-04-23 09:37:41 +08:00
using UnityEngine.EventSystems;
using UnityEngine.Events;
using Assets.Scenes.Ride.Scripts.Model.RiderModels;
using System.IO;
using ChartAndGraph;
using UnityEngine.UI;
2021-07-09 18:16:50 +08:00
using System.Diagnostics;
using UnityEngine.SceneManagement;
public class CyclingController : DeviceServiceMonoBase
{
public AbstractMap map;
public GameObject player;
public GameObject UIObject;
public RouteResultParam selectParamModel;
public RouteResult routeResult;
2021-04-19 18:03:04 +08:00
2021-11-16 18:03:56 +08:00
public GameObject minicamera;
public Dictionary<int, SeletedPlayerScript> selectPlayerDic { set; get; } = new Dictionary<int, SeletedPlayerScript>();
public int preticks { get; set; }
#region
public MapRoute mapRoute { get; set; }//当前路书数据
public MapCompetition competition { get; set; }//当前赛事数据
private MapDataModel mapData { get; set; }//当前路书数据
private Route route { get; set; }//当前路书综合数据
public List<MapRouteRanking> mapRouteRankingList { get; set; }
private Vector2d coordiantes;//当前地图中心
2021-04-15 10:13:01 +08:00
public bool isStart { get; set; }//当前游戏是否开始
public CyclingModel cyclingModel { get; set; }//当前骑行模式
public BaseCycling cyclingController { get; set; }
2021-04-22 19:29:59 +08:00
private int routeId;
public int competitionId { get; set; }
private MapApi mapApi;
2021-07-09 18:16:50 +08:00
public DateTime startTime { get; set; }
2021-04-19 18:03:04 +08:00
public DateTime endTime;
public bool isQuit;
public bool isPause;
#endregion
2021-04-16 11:23:18 +08:00
GameObject loadingcanvas;
AbstratctLoadingController loadingController;
2021-04-21 14:08:45 +08:00
private async Task Login()
{
var result = await new UserApi().Login("15261826280", "123456", "");
2021-04-21 14:08:45 +08:00
App.CurrentUser = result.data;
}
GameObject miniMap { get; set; }
2021-04-22 19:29:59 +08:00
GameObject resultPanel;
public ChartDataSourceScript chartDataSourceScript { get; set; }
public GraphChartBase graph { get; set; }
2021-09-02 10:08:46 +08:00
private float activeSeconds { get; set; }//移动端用户进入骑行超过2min界面进入沉浸状态
protected override void Awake()
{
base.Awake();
#if UNITY_EDITOR
2021-04-29 22:16:32 +08:00
if (App.CurrentUser == null)
{
2021-04-21 14:08:45 +08:00
Login();
2021-04-29 22:16:32 +08:00
}
#endif
//获取路书信息
mapApi = ConfigHelper.mapApi;
routeId = App.RouteIdParam > 0 ? App.RouteIdParam : 2633;
competitionId = App.CompetionId;
App.CompetionId = 0;//清空比赛参数
//处理异常中断的骑行
if (App.tempRecordData != null)
{
selectParamModel = App.tempRecordData.selectParam;
competitionId = selectParamModel.CompetitionId ?? 0;
routeId = selectParamModel.RouteId ?? 0;
}
2021-09-13 18:21:43 +08:00
Resources.UnloadUnusedAssets();
}
2021-04-22 19:29:59 +08:00
void OnDestroy()
{
2021-12-15 13:24:26 +08:00
//MapUDPService.Dispose();
2021-09-13 18:21:43 +08:00
Resources.UnloadUnusedAssets();
GC.Collect();
}
Transform target;
GameObject watcher;
Transform uiParent;
2021-09-02 10:08:46 +08:00
GameObject uipanel { get; set; }
GameObject onlineUserPrefab3d { get; set; }
GameObject OnlineHeadPanel { get; set; }
public GameObject GetOnlineheadPanel()
{
if (OnlineHeadPanel == null)
{
OnlineHeadPanel = Resources.Load<GameObject>("UI/Prefab/Ride/OnlineHeadPanel");
}
return OnlineHeadPanel;
}
Material Graph3d { get; set; }
Material Graph4 { get; set; }
Material Graph1 { get; set; }
public Material Get3dGraph2()
{
if (Graph3d == null)
{
Graph3d = Resources.Load<Material>("UI/Material/3dGraph2");
}
return Graph3d;
}
public Material GetMaterial4()
{
if (Graph4 == null)
{
Graph4 = Resources.Load<Material>("UI/Material/4");
}
return Graph4;
}
public Material GetMaterial1()
{
if (Graph1 == null)
{
Graph1 = Resources.Load<Material>("UI/Material/1");
}
return Graph1;
}
Image CompetitionArrow { get; set; }
public Image GetCompetitionArrow()
{
if (CompetitionArrow == null)
{
CompetitionArrow = Resources.Load<Image>("UI/Prefab/Match/CompetitionArrow");
}
return CompetitionArrow;
}
Image CompetitionMobileArrow { get; set; }
public Image GetCompetitionMobileArrow()
{
if (CompetitionMobileArrow == null)
{
CompetitionMobileArrow = Resources.Load<Image>("UI/Prefab/Match/Mobile/CompetitionArrow");
}
return CompetitionMobileArrow;
}
2021-04-15 17:09:35 +08:00
private void Start()
{
2021-09-02 10:08:46 +08:00
var uicanvasScaler = UIObject.GetComponent<CanvasScaler>();
var loadingcanvasScaler = transform.Find("LoadingCanvas").GetComponent<CanvasScaler>();
#if UNITY_ANDROID || UNITY_IOS
uipanel = Instantiate(Resources.Load<GameObject>("UI/Prefab/Ride/Mobile/Panel"), UIObject.transform);
uicanvasScaler.referenceResolution = App.MobileResolution;
loadingcanvasScaler.referenceResolution = App.MobileResolution;
#else
uipanel = Instantiate(Resources.Load<GameObject>("UI/Prefab/Ride/Panel"), UIObject.transform);
uicanvasScaler.referenceResolution = App.PcResolution;
loadingcanvasScaler.referenceResolution = App.PcResolution;
2021-11-04 13:24:40 +08:00
var modalRect = transform.Find("UI/ModalPanel").GetComponent<RectTransform>();
modalRect.anchorMin = new Vector2(0.5f, 0.5f);
modalRect.anchorMax = new Vector2(0.5f, 0.5f);
modalRect.offsetMin = Vector2.zero;
modalRect.offsetMax = Vector2.zero;
modalRect.sizeDelta = new Vector2(1600, 900);
2021-09-02 10:08:46 +08:00
#endif
uipanel.transform.SetAsFirstSibling();
uiParent = uipanel.transform;
resultPanel = uiParent.Find("ResultPanel").gameObject;
//获取海拔图UI对象
var graphObject = uiParent.Find("GraphChart");
chartDataSourceScript = graphObject.GetComponent<ChartDataSourceScript>();
graph = graphObject.GetComponent<GraphChartBase>();
UIManager.Instance.MainPanel = uipanel.GetComponent<PFUIPanel>();
UIManager.Instance.ModalsPanel = this.transform.Find("UI/ModalPanel").GetComponent<PFUIPanel>();
onlineUserPrefab = Resources.Load<GameObject>("UI/Prefab/Ride/EmptyOnlinePlayer");
onlineUserPrefab3d = Resources.Load<GameObject>("UI/Prefab/Match/onlinePlayerNoScript");
miniMapPlayerPrefab = Resources.Load<GameObject>("UI/Prefab/Ride/MiniMapPlayer");
watcher = Resources.Load<GameObject>("UI/Prefab/Match/Watcher");
target = transform.Find("Target");
miniMap = transform.Find("MiniMap").gameObject;//小地图
2021-11-16 18:03:56 +08:00
minicamera = transform.Find("MiniCamera").gameObject;
2021-04-30 17:25:28 +08:00
//进入倒计时
singleUIManager = UIObject.GetComponent<BaseUIManager>();
TrailRenderer trail = player.GetComponent<TrailRenderer>();
trail.Clear();
playerController = player.GetComponent<PlayerController>();
currentPlayer = playerController;//当前选中用户
if (competitionId > 0)
{
loadingController = transform.Find("LoadingCanvas").gameObject.AddComponent<CompetitionLoadingController>();
}
else
{
loadingController = transform.Find("LoadingCanvas").gameObject.AddComponent<LoadingController>();
}
//loadingController = FindObjectOfType<LoadingController>();
//
2021-04-22 19:29:59 +08:00
loadingController.InjectController(this);
SceneManager.activeSceneChanged += SceneManager_activeSceneChanged;
//进入比赛
if (competitionId > 0)
{
2021-07-28 18:56:23 +08:00
this.cyclingModel = CyclingModel.Competition;
StartCoroutine(InitRace());
return;
}
//进入单人骑行
if (routeId > 0)
{
StartCoroutine(Init());
return;
}
2021-04-22 19:29:59 +08:00
}
float timer = 1f;
2021-09-02 10:08:46 +08:00
bool clearLock = false;
private void SceneManager_activeSceneChanged(Scene arg0, Scene arg1)
{
ClearTempFile();
}
/// <summary>
/// 检测是否点击UI
/// </summary>
/// <param name="mousePosition"></param>
/// <returns></returns>
private bool IsPointerOverGameObject(Vector2 mousePosition)
{
//创建一个点击事件
PointerEventData eventData = new PointerEventData(EventSystem.current);
eventData.position = mousePosition;
List<RaycastResult> raycastResults = new List<RaycastResult>();
//向点击位置发射一条射线检测是否点击UI
EventSystem.current.RaycastAll(eventData, raycastResults);
if (raycastResults.Count > 0)
{
2021-12-07 17:43:32 +08:00
return !raycastResults.Where(c => c.gameObject.name == "NearPanel" || c.gameObject.name == "ToolBarPanel" || c.gameObject.name == "SettingPanel" || c.gameObject.name == "QuitPanel").Any();
}
else
{
return false;
}
}
bool _dragStartedOnUI = false;
2021-11-09 11:37:10 +08:00
protected override void Update()
{
2021-11-09 11:37:10 +08:00
base.Update();
//CamControl();
timer -= Time.deltaTime;
if (timer <= 0)//定时器 一秒执行一次
{
TcpHandler();
2021-07-29 20:01:38 +08:00
App.CurrentScene = "Ride";
if (competitionId == 0)
{
UIManager.SendCompetitionStartMessage("Ride");
}
#if UNITY_IOS || UNITY_ANDROID
//if (isStart)
//{
// activeSeconds++;
//}
//if (activeSeconds >= App.autoClearTimes && !clearLock)
//{
// if (competitionId == 0)
// {
// clearLock = true;
// singleUIManager?.ClearPanel(null);
// }
//}
#endif
2021-09-02 10:08:46 +08:00
timer += 1.0f;
}
}
2021-12-09 18:17:39 +08:00
float touchTimer = 0.1f;
private void FixedUpdate()
{
2021-12-09 18:17:39 +08:00
touchTimer -= Time.deltaTime;
if (touchTimer <= 0)
{
2021-12-09 18:17:39 +08:00
#if UNITY_IOS || UNITY_ANDROID
HandleTouch();
2021-12-09 18:17:39 +08:00
#else
HandleMouseScrollWheel();
#endif
2021-12-09 18:17:39 +08:00
touchTimer += 0.1f;
}
}
public bool isWatch { get; set; }
private Vector3 currentCameraPos { get; set; }
Vector3 far = new Vector3(-25, 73, -70);
Vector3 plane = new Vector3(-15, 43, -40);
Vector3 near = new Vector3(-8, 23, -20);
List<Vector3> cameraList { get; set; }
2021-12-09 18:17:39 +08:00
/// <summary>
/// 处理PC端
/// </summary>
private void HandleMouseScrollWheel()
{
var scrollDelta = Input.GetAxis("Mouse ScrollWheel");
UnityEngine.Debug.Log($"scrolldelta{scrollDelta}");
if (cameraList == null)
{
cameraList = new List<Vector3>();
cameraList.Add(near);
cameraList.Add(plane);
cameraList.Add(far);
}
var prePos = Camera.main.transform.localPosition;
var nextPos = Camera.main.transform.localPosition;
if (scrollDelta < 0)
{
nextPos = cameraList.Where(c => c.y > Camera.main.transform.localPosition.y).FirstOrDefault();
if (nextPos != Vector3.zero)
StartCoroutine(MoveCamera(prePos, nextPos));
}
if (scrollDelta > 0)
{
nextPos = cameraList.Where(c => c.y < Camera.main.transform.localPosition.y).LastOrDefault();
if (nextPos != Vector3.zero)
StartCoroutine(MoveCamera(prePos, nextPos));
}
}
private void HandleTouch()
{
2021-12-09 18:17:39 +08:00
if (singleUIManager == null)
return;
var touchCount = Input.touchCount;
switch (Input.touchCount)
{
case 1:
{
//单击切换极简模式
2021-12-09 18:17:39 +08:00
if (Input.touches[0].tapCount==1 && isStart && singleUIManager.clearLock && competitionId == 0)
{
if (IsPointerOverGameObject(Input.mousePosition))
{
singleUIManager?.ClearPanel(null);
}
}
}
break;
case 2:
{
//双手触摸移动摄像机
// Store both touches.
Touch touchZero = Input.GetTouch(0);
Touch touchOne = Input.GetTouch(1);
// Find the position in the previous frame of each touch.
Vector2 touchZeroPrevPos = touchZero.position - touchZero.deltaPosition;
Vector2 touchOnePrevPos = touchOne.position - touchOne.deltaPosition;
// Find the magnitude of the vector (the distance) between the touches in each frame.
float prevTouchDeltaMag = (touchZeroPrevPos - touchOnePrevPos).magnitude;
float touchDeltaMag = (touchZero.position - touchOne.position).magnitude;
var offset = touchDeltaMag - prevTouchDeltaMag;
if (cameraList == null)
{
cameraList = new List<Vector3>();
cameraList.Add(near);
cameraList.Add(plane);
cameraList.Add(far);
}
var prePos = Camera.main.transform.localPosition;
var nextPos = Camera.main.transform.localPosition;
if (offset < 0)
{
nextPos = cameraList.Where(c => c.y > Camera.main.transform.localPosition.y).FirstOrDefault();
if (nextPos != Vector3.zero)
StartCoroutine(MoveCamera(prePos, nextPos));
}
if (offset > 0)
{
nextPos = cameraList.Where(c => c.y < Camera.main.transform.localPosition.y).LastOrDefault();
if (nextPos != Vector3.zero)
StartCoroutine(MoveCamera(prePos, nextPos));
}
}
break;
}
2021-12-09 18:17:39 +08:00
}
2021-04-22 19:29:59 +08:00
/// <summary>
/// 处理中断骑行
/// </summary>
private void TempFileHandler()
{
//处理异常中断的骑行
if (App.tempRecordData != null)
{
recorderData.EndDistance = App.tempRecordData.EndDistance;
recorderData.StartTime = App.tempRecordData.StartTime;
recorderData.RiderDatas = App.tempRecordData.RiderDatas;
coordiantes = Along(App.tempRecordData.EndDistance);
startTime = App.tempRecordData.StartTime;
preticks = recorderData.RiderDatas.Last().Ticks;
App.tempRecordData = null;//清空
}
}
private IEnumerator Init()
2021-04-15 10:13:01 +08:00
{
2021-04-25 19:41:35 +08:00
yield return new WaitForSeconds(1);
mapRoute = mapApi.GetById(routeId).data;
loadingController.Init();//初始化loading页面
2021-04-22 19:29:59 +08:00
loadingController.AddProcess(10);
InitData();//初始化数据
InitGameObject();//初始化场景
2021-04-25 19:41:35 +08:00
MapUDPService.Init();//初始化TCP
loadingController.AddProcess(10);
2021-04-22 19:29:59 +08:00
}
//初始比赛
private IEnumerator InitRace()
{
yield return new WaitForSeconds(1);
mapRoute = mapApi.GetById(routeId).data;
var mapCompetitionApi = new MapCompetitionApi();
competition = mapCompetitionApi.GetById(competitionId).data;
loadingController.Init();//初始化loading页面
loadingController.AddProcess(10);
InitRaceData();//初始化比赛数据
InitRaceGameObject();//初始化比赛场景
//MapUDPService.Init(competitionId,isWatch);//初始化比赛TCP
loadingController.AddProcess(10);
}
public void InitTcp()
{
MapUDPService.Init(competitionId, isWatch);//初始化比赛TCP
}
2021-04-22 19:29:59 +08:00
//初始化数据
private void InitData()
{
mapData = mapApi.GetData(routeId);//获取路书地理数据
route = new Route(mapData, mapRoute);
loadingController.AddProcess(10);
#region
2021-04-22 19:29:59 +08:00
//骑行结果
if (App.routeResult != null)
{
routeResult = App.routeResult;
2021-04-22 19:29:59 +08:00
selectParamModel = App.routeResult.ContinueCyclingParam;//继续骑行
preticks = App.routeResult.Ticks;
}
if (selectParamModel == null)
{
selectParamModel = new RouteResultParam
{
CompetitionId = 0,
ContinueIndex = 0,
ContinueMark = "",
GlobalContinue = false,
EndDistance = 0,
RankingsId = new List<string>(),
OnlineUserId = 0,
RouteId = App.RouteIdParam
};
}
App.routeResult = null;
#endregion
2021-04-22 19:29:59 +08:00
double endDistance = selectParamModel.EndDistance;
coordiantes = Along(endDistance);
var shaowList = mapApi.GetShadowList(routeId, "", 0, 10);
if (shaowList.result)
{
mapRouteRankingList = shaowList.data.list;
2021-04-22 19:29:59 +08:00
}
}
private void InitRaceData()
{
mapData = mapApi.GetData(routeId);//获取路书地理数据
route = new Route(mapData, mapRoute);
loadingController.AddProcess(10);
#region
selectParamModel = new RouteResultParam
{
CompetitionId = competitionId,
ContinueIndex = 0,
ContinueMark = "",
GlobalContinue = false,
EndDistance = 0,
RankingsId = new List<string>(),
OnlineUserId = 0,
RouteId = App.RouteIdParam
};
#endregion
double endDistance = selectParamModel.EndDistance;
//计算上次骑行距离调整地图中心点
coordiantes = Along(endDistance);
}
private Vector3 mapPos = Vector3.zero;
2021-04-22 19:29:59 +08:00
//加载人物和地图以及UI界面
private void InitGameObject()
{
2021-11-16 18:03:56 +08:00
#if !(UNITY_IOS || UNITY_ANDROID)
minicamera.SetActive(true);
miniMap.SetActive(true);
#endif
map.gameObject.SetActive(true);
2021-04-16 11:23:18 +08:00
player.SetActive(true);
UIObject.SetActive(true);
singleUIManager = UIObject.AddComponent<SingleUIManager>();
2021-04-30 17:45:21 +08:00
map.OnTileFinished += Map_OnTileFinished;
mapPos = map.transform.position;
2021-04-30 17:45:21 +08:00
}
private void InitRaceGameObject()
{
2021-11-16 18:03:56 +08:00
#if !(UNITY_IOS || UNITY_ANDROID)
minicamera.SetActive(true);
#endif
map.gameObject.SetActive(true);
player.SetActive(true);
UIObject.SetActive(true);
singleUIManager = UIObject.AddComponent<CompetitionUIManager>();
//miniMap.SetActive(true);
map.OnTileFinished += Map_OnTileFinished;
mapPos = map.transform.position;
2021-07-09 18:16:50 +08:00
//为了解决比赛观看模式下,切换观看用户之前跨度过大导致地图海拔信息不完整的问题
RangeAroundTransformTileProviderOptions options = new RangeAroundTransformTileProviderOptions
{
targetTransform = target,
visibleBuffer = 2,
disposeBuffer = 2
2021-07-09 18:16:50 +08:00
};
map.SetExtent(MapExtentType.RangeAroundTransform, options);
map.SetExtentOptions(options);
}
2021-04-21 14:08:45 +08:00
//设置骑行模式
public void SetCyclingModel(CyclingModel mode)
{
this.cyclingModel = mode;
switch (cyclingModel)
{
case CyclingModel.Single:
2021-04-22 19:29:59 +08:00
cyclingController = new SingleModel(route, selectParamModel);
break;
case CyclingModel.Review:
2021-04-28 15:37:18 +08:00
cyclingController = new ReviewModel(route, selectParamModel);
break;
case CyclingModel.Competition:
cyclingController = new CompetitionModel(route, selectParamModel, currentPlayer);
break;
}
GameStart();
InitPlayer();//初始化人物方向等
}
PlayerController playerController;
public AbstractPlayer currentPlayer { get; set; }
private GameObject onlinePlayer { get; set; }
Vector3 MAX_SIZE = new Vector3(3f, 3f, 3f);
Vector3 MIN_SIZE = new Vector3(1f, 1f, 1f);
public void ChangeCurrentPlayer(int userId)
{
var coll = FindObjectsOfType<AbstractPlayer>();
var selectedPlayer = coll.Where(c => c.UserId == userId).FirstOrDefault();
if (selectedPlayer != null)
{
currentPlayer = selectedPlayer;
if (selectedPlayer is PlayerController)
{
selectedPlayer.transform.localScale = Is3dView ? MAX_SIZE : MIN_SIZE;
}
else
{
Utils.DestroyChildren(selectedPlayer.transform);
var ss = Instantiate(onlineUserPrefab3d, selectedPlayer.transform);
ss.transform.localScale = Is3dView ? MAX_SIZE : MIN_SIZE;
}
2021-07-09 18:16:50 +08:00
}
2021-07-09 18:16:50 +08:00
var unselectedPlayers = coll.Where(c => c.UserId != userId).ToList();
foreach (var item in unselectedPlayers)
{
item.transform.localScale = MIN_SIZE;
if (item.transform.childCount > 0)
{
Utils.DestroyChildren(item.transform);
}
}
//重置海拔图进度
var currentIndex = currentPlayer.CurrentIndex;
graph.HorizontalScrolling = chartDataSourceScript.GetCurrentStart(currentIndex);
}
2021-09-28 11:30:51 +08:00
//初始化人物位置角度
private void InitPlayer()
{
TempFileHandler();//处理中断骑行继续骑的逻辑
lockView = true;
Vector2d lastLatLon = Along(recorderData.EndDistance);
Vector3 currentPos = map.GeoToWorldPosition(lastLatLon);
currentPos.y += 1f;
player.transform.position = currentPos;
playerController.currentPos = currentPos;
var trail = FindObjectOfType<TrailRenderer>();
trail.enabled = true;
Vector2d nextLatLon = Along(recorderData.EndDistance + 0.1);
//设定人物方向
var s = map.GeoToWorldPosition(lastLatLon);
var e = map.GeoToWorldPosition(nextLatLon);
Quaternion neededRotation = Quaternion.LookRotation(s - e);
player.transform.rotation = Quaternion.Euler(0, neededRotation.eulerAngles.y, 0);
playerController.currentRotation = neededRotation;
//初始化海拔图头像位置
var index = GetCurrentIndex(recorderData.EndDistance);
InitGraph(index);
int tick = 0;
if (recorderData.RiderDatas.Count > 0)
{
tick = recorderData.RiderDatas.Last().Ticks;
}
playerController.Init(index, recorderData.EndDistance, tick);
}
public void InitGraph(int index)
{
chartDataSourceScript.InitHorizontalScrolling(index);
2021-04-30 17:25:28 +08:00
}
private IEnumerator MoveCamera(Vector3 prePos, Vector3 nextPos)
{
float t = 0;
2021-12-09 18:17:39 +08:00
while (t < 0.5f)
{
t += Time.deltaTime;
Vector3 v = Vector3.Lerp(prePos, nextPos, t);
Camera.main.transform.localPosition = v;
yield return new WaitForEndOfFrame();
}
}
//SingleUIManager singleUIManager;
public BaseUIManager singleUIManager;
public void GameStart()
2021-04-30 17:25:28 +08:00
{
StartCoroutine(MoveCamera(far, plane));//初始摄像头
var check = CheckAnt();
2021-11-11 15:55:58 +08:00
#if UNITY_EDITOR
check = true;
#endif
if (check || isWatch)
{
singleUIManager.StartRide();
transform.Find("UI/Panel(Clone)/ToolBarPanel/StartOrPauseButton").GetComponent<Button>().enabled = true;
2021-11-02 17:55:49 +08:00
transform.Find("UI/Panel(Clone)/ToolBarPanel/SettingButton").GetComponent<Button>().enabled = true;
}
else
{
transform.Find("UI/Panel(Clone)/ToolBarPanel/StartOrPauseButton").GetComponent<Button>().enabled = false;
2021-11-02 17:55:49 +08:00
transform.Find("UI/Panel(Clone)/ToolBarPanel/SettingButton").GetComponent<Button>().enabled = false;
Utils.showToast(null, "Please connect the device!", duration: int.MaxValue, isLowest: true
, stopFunc: () => isWatch || CheckAnt() || transform.Find("UI/Panel(Clone)/SelectPlayer").gameObject.activeInHierarchy
, endCallback: () =>
{
if (!transform.Find("UI/Panel(Clone)/SelectPlayer").gameObject.activeInHierarchy)
2021-11-04 13:24:40 +08:00
{
UIManager.Instance.DevicePanel.Close();
singleUIManager.StartRide();
transform.Find("UI/Panel(Clone)/ToolBarPanel/StartOrPauseButton").GetComponent<Button>().enabled = true;
transform.Find("UI/Panel(Clone)/ToolBarPanel/SettingButton").GetComponent<Button>().enabled = true;
}
});
}
}
2021-04-30 17:25:28 +08:00
public void GoContinueRide()
{
singleUIManager.ContinueRide();
2021-04-30 17:25:28 +08:00
}
#region TCP相关
public void TcpHandler()
{
if (cyclingController != null)
{
2021-09-17 22:20:05 +08:00
////tcp数据传输
//if (competition != null && !cyclingController.recorderData.Saved)
//{
// cyclingController.recorderData.Saved = competition.HasRecord;
//}
cyclingController.Run(null);
//在线人物或比赛人物渲染
ShowOnlineUsers();
}
}
List<OnlinePlayerController> otherList = new List<OnlinePlayerController>();
GameObject onlineUserPrefab;
GameObject miniMapPlayerPrefab;
int messageIndex = 0;
private void ShowOnlineUsers()
{
var onlineRiders = cyclingController.riders;
var currentOnlineUserList = FindObjectsOfType<OnlinePlayerController>();
//新增或者更新
foreach (var item in onlineRiders)
{
var onlineRider = item as OnlineRiderModel;
var currentUser = currentOnlineUserList.Where(c => c.UserId == item.UserId).FirstOrDefault();
var onlineDistance = onlineRider.EndDistance - onlineRider.PreDistance;
var onlineTotalDistance = onlineRider.PreDistance;
var index = GetCurrentIndex(onlineTotalDistance);
if (currentUser == null)
{
//大地图人物
GameObject otherPlayerObj = (GameObject)Instantiate(onlineUserPrefab, transform);
otherPlayerObj.transform.position = map.GeoToWorldPosition(Along(onlineTotalDistance));
var onlinePlayerController = otherPlayerObj.GetComponent<OnlinePlayerController>();
otherList.Add(onlinePlayerController);
onlinePlayerController.UserId = onlineRider.UserId;
onlinePlayerController.SetDataSource(onlineTotalDistance, onlineDistance, onlineRider.Power, onlineRider.HeartRate, onlineRider.Cadence, onlineRider.TotalTicks, onlineRider.NickName, onlineRider.WeightKg, new Vector2d(onlineRider.Point.Latitude, onlineRider.Point.Longitude), index);
onlinePlayerController.SetHead(onlineRider.WxHeadImg);
2021-09-16 15:59:08 +08:00
if (competitionId == 0)
{
//小地图人物
GameObject miniPlayer = (GameObject)Instantiate(miniMapPlayerPrefab, transform);
var miniController = miniPlayer.GetComponent<MiniMapPlayerController>();
miniController.SetController(onlinePlayerController);
}
//发消息xx进入路书
if (messageIndex > 0)
EventQueueSystem.QueueEvent(new JoinMessageEvent(onlineRider.NickName, onlineRider.WxHeadImg));
}
else
{
currentUser.SetDataSource(onlineTotalDistance, onlineDistance, onlineRider.Power, onlineRider.HeartRate, onlineRider.Cadence, onlineRider.TotalTicks, onlineRider.NickName, onlineRider.WeightKg, new Vector2d(onlineRider.Point.Latitude, onlineRider.Point.Longitude), index);
}
//如果是观察者且当前第一此进入场景(TODO这样切换会闪一下待解决)
if (isWatch && (currentPlayer is PlayerController || currentPlayer == null))
{
var userId = onlineRiders.FirstOrDefault()?.UserId ?? 0;
ChangeCurrentPlayer(userId);
var competitionRankingFactory = FindObjectOfType<CompetitionRankingFactory>();
if (competitionRankingFactory != null)
{
competitionRankingFactory.isInit = false;
}
}
//显示观察者头像
}
if (onlineRiders.Count > 0)
messageIndex++;
//移除
foreach (var item in currentOnlineUserList)
{
var currentItem = onlineRiders.Where(c => c.UserId == item.UserId).FirstOrDefault();
if (currentItem == null)
{
item.RemoveSelf();
}
}
//显示面板信息
var others = FindObjectsOfType<AbstractPlayer>();
foreach (var item in others)
{
item.IsShowInfo = false;
}
var frontPlayer = others.Where(c => c.TotalDistance - currentPlayer.TotalDistance < 0.25 && c.TotalDistance - currentPlayer.TotalDistance >= 0 && c.UserId != currentPlayer.UserId).OrderBy(c => c.TotalDistance).FirstOrDefault();
var bakePlayer = others.Where(c => c.TotalDistance - currentPlayer.TotalDistance > -0.25 && c.TotalDistance - currentPlayer.TotalDistance < 0 && c.UserId != currentPlayer.UserId).OrderByDescending(c => c.TotalDistance).FirstOrDefault();
if (frontPlayer != null)
frontPlayer.IsShowInfo = true;
if (bakePlayer != null)
bakePlayer.IsShowInfo = true;
}
//查询赛事观看者列表(取前5)
public List<OnlineUser> GetWatcherList()
{
return MapUDPService.GetCompetitionWatchers(competitionId);
}
#endregion
public void SetUIManager(PFUIPanel mainPanel, PFUIPanel model)
{
UIManager.Instance.MainPanel = mainPanel;
UIManager.Instance.ModalsPanel = model;
}
public void ReSetUIManager()
{
2021-09-02 10:08:46 +08:00
UIManager.Instance.MainPanel = uipanel.GetComponent<PFUIPanel>();
UIManager.Instance.ModalsPanel = this.transform.Find("UI/ModalPanel").GetComponent<PFUIPanel>();
}
public void AddEvent(GameObject sender, EventTriggerType eventType, UnityAction<BaseEventData> unityAction)
{
UIManager.AddEvent(sender, eventType, unityAction);
}
public void ShowDevice(PFUIPanel pFUIPanel)
{
2021-09-02 11:04:50 +08:00
#if UNITY_IOS || UNITY_ANDROID
UIManager.ShowDevicePanel();
#else
2021-11-02 17:55:49 +08:00
UIManager.Show(UIManager.Instance.DevicePanel,null,true);
2021-09-02 11:04:50 +08:00
#endif
}
public Texture GetCountryImageByCode(string code)
{
return UIManager.Instance.loginRegOptions.GetCountryImage(code);
}
public Texture GetCountryImageByName(string name)
{
return UIManager.Instance.loginRegOptions.GetCountryImageByName(name);
}
#region
public AbstractMap map3d;
2021-04-21 14:08:45 +08:00
public bool Is3dView;
public void ChangeMapImageStyle(GameObject arrowGameObj)
{
var trailRendererList = transform.GetComponentsInChildren<TrailRenderer>();
foreach (var item in trailRendererList)
{
item.time = 0;
}
StartCoroutine(EnableTrailRenderer(trailRendererList.ToList()));
2021-04-21 14:08:45 +08:00
if (!Is3dView)
{
//地图属性变更
2021-04-21 14:08:45 +08:00
map.Terrain.ExaggerationFactor = 1.5f;
map.Terrain.SetElevationType(ElevationLayerType.TerrainWithElevation);
map.ImageLayer.SetLayerSource(ImagerySourceType.Custom);
map.SetCenterLatitudeLongitude(currentPlayer.Currentlatlong);
map.transform.position = mapPos;
//map3d.gameObject.SetActive(true);
//map.gameObject.SetActive(false);
//人物属性变更
var pos = map.GeoToWorldPosition(currentPlayer.Currentlatlong);
playerController.currentPos = pos;
target.position = pos;
player.transform.localScale = new Vector3(3f, 3f, 3f);
player.transform.position = pos;
2021-04-21 14:08:45 +08:00
arrowGameObj.SetActive(false);
Is3dView = true;
2021-04-21 14:08:45 +08:00
}
else
{
//地图属性变更
map.ImageLayer.SetLayerSource(ImagerySourceType.JuzeTest);
map.Terrain.ExaggerationFactor = 0f;
map.Terrain.SetElevationType(ElevationLayerType.FlatTerrain);
map.SetCenterLatitudeLongitude(currentPlayer.Currentlatlong);
map.transform.position = Vector3.zero;
//map.gameObject.SetActive(true);
//map3d.gameObject.SetActive(false);
//人物属性变更
var pos = map.GeoToWorldPosition(currentPlayer.Currentlatlong);
player.transform.position = pos;
player.transform.localScale = new Vector3(0.01f, 0.01f, 0.01f);
target.position = pos;
//playerController.currentPos = Vector3.zero;
arrowGameObj.SetActive(true);
Is3dView = false;
}
if (competitionId > 0)
{
ChangeCurrentPlayer(currentPlayer.UserId);
}
}
private bool lockView = false;
private void Map_OnTileFinished(Mapbox.Unity.MeshGeneration.Data.UnityTile obj)
{
if (!lockView)
{
var playerController = player.GetComponent<PlayerController>();
player.transform.localScale = new Vector3(3f, 3f, 3f);
var locations = playerController.Currentlatlong == null ? playerController.Currentlatlong : new Vector2d(mapData.List[0].Point[0], mapData.List[0].Point[1]);
player.transform.position = map.GeoToWorldPosition(locations);
mapPos = map.transform.position;
if (recorderData != null)
{
var lastLatLon = Along(recorderData.EndDistance);
var nextLatLon = Along(recorderData.EndDistance + 0.1);
player.transform.position = map.GeoToWorldPosition(lastLatLon);
//设定人物方向
var s = map.GeoToWorldPosition(lastLatLon);
var e = map.GeoToWorldPosition(nextLatLon);
Quaternion neededRotation = Quaternion.LookRotation(s - e);
player.transform.rotation = Quaternion.Euler(0, neededRotation.eulerAngles.y, 0);
}
2021-04-21 14:08:45 +08:00
}
}
IEnumerator EnableTrailRenderer(List<TrailRenderer> trailRendererList)
2021-04-27 15:15:51 +08:00
{
yield return new WaitForSeconds(2f);
foreach (var item in trailRendererList)
{
item.Clear();
item.time = 30;
}
2021-04-27 15:15:51 +08:00
}
#endregion
2021-04-21 14:08:45 +08:00
#region
2021-07-09 18:16:50 +08:00
Stopwatch sw { get; set; }
2021-04-19 18:03:04 +08:00
//开始骑行
public void SetStart()
{
if (!isPause && DateTime.MinValue == startTime)
2021-04-19 18:03:04 +08:00
{
isStart = true;
2021-05-08 18:36:59 +08:00
startTime = UIManager.Now.GetDateTime();
2021-07-30 09:53:49 +08:00
////骑行累计毫秒
//sw = new Stopwatch();
//sw.Start();
2021-09-02 10:08:46 +08:00
activeSeconds = 0f;
2021-04-19 18:03:04 +08:00
}
else
{
SetContinue();
}
}
//继续骑行
public void SetContinue()
{
isStart = true;
isPause = false;
}
//暂停骑行
public void SetPause()
{
isStart = false;
isPause = true;
}
//退出或者完成骑行
public void SetQuit()
{
2021-07-30 09:53:49 +08:00
////耗时巨大的代码
//if (sw != null)
//{
// sw.Stop();
// TimeSpan ts2 = (TimeSpan)(sw.Elapsed);
// UnityEngine.Debug.Log(string.Format("Stopwatch总共花费{0}ms.", ts2.TotalMilliseconds));
// //TODO后算接口需要增加累计毫秒字段
//}
2021-04-19 18:03:04 +08:00
isStart = false;
isQuit = true;
}
#endregion
2021-04-19 18:03:04 +08:00
#region
/// <summary>
/// 当前骑行数据的记录器
/// </summary>
private RecorderDataModel recorderData
{
get
{
return cyclingController?.recorderData;
}
}
public Route GetRoute()
{
2021-04-22 19:29:59 +08:00
return route;
}
2021-09-02 10:08:46 +08:00
public GameObject GetUIPanel()
{
return uipanel;
}
public MapDataModel GetMapData()
{
return mapData;
}
/// <summary>
/// 清空临时文件
/// </summary>
public void ClearTempFile()
{
Helper.DelectDir(PFConstants.MapWorkoutRecordTempFolder);
App.tempRecordData = null;
}
TempRecordData tempRecordData { get; set; }
public void SaveRealTime()
{
if (tempRecordData == null)
{
tempRecordData = new TempRecordData();
}
RecorderDataModel recorderData = cyclingController.recorderData;
tempRecordData.RiderDatas = recorderData.RiderDatas;
tempRecordData.selectParam = recorderData.selectParam;
tempRecordData.RouteId = mapRoute.Id;
tempRecordData.StartTime = startTime;
tempRecordData.ManufacturerId = recorderData.ManufacturerId;
tempRecordData.ManufacturerName = recorderData.ManufacturerName;
tempRecordData.Mode = cyclingModel.ToString();
tempRecordData.EndDistance = recorderData.EndDistance;
var guid = recorderData.ContinueMark;
var filePath = PFConstants.MapWorkoutRecordTempFolder + "/" + guid.ToString()+".txt";
var tempContent = Newtonsoft.Json.JsonConvert.SerializeObject(tempRecordData);
System.IO.File.WriteAllText(filePath, tempContent);
}
2021-04-22 19:29:59 +08:00
2021-04-19 18:03:04 +08:00
public void Save(double totalDistance)
{
ClearTempFile();
2021-07-30 19:39:01 +08:00
cyclingController.recorderData.EndTime = UIManager.Now.GetDateTime();
2021-04-27 15:15:51 +08:00
isQuit = true;
2021-04-19 18:03:04 +08:00
isStart = false;
string recordId = Guid.NewGuid().ToString();
//var path = Helper.GetDataDir("MapWorkoutRecords/"+ recordId);
var path = PFConstants.MapWorkoutRecordFolder + "/" + recordId;
Helper.CreateDirectoryIfNotExsit(path);
string imageFileName = path +"/"+ Guid.NewGuid().ToString() + ".png";
CaptureCamera(Camera.main, new Rect(Screen.width * 0f, Screen.height * 0f, Screen.width * 0.5f, Screen.height * 0.5f), imageFileName);
2021-04-19 18:03:04 +08:00
cyclingController.recorderData.StartTime = startTime;
2021-07-30 19:39:01 +08:00
cyclingController.recorderData.IsCompleted = totalDistance >= mapData.TotalDistance;
2021-04-19 18:03:04 +08:00
cyclingController.recorderData.EndDistance = totalDistance;
cyclingController.recorderData.AntModelId = AntModelId;
cyclingController.recorderData.ManufacturerId = ManufacturerId;
2021-06-08 16:28:00 +08:00
cyclingController.recorderData.ManufacturerName = ManufacturerName;
2021-04-19 18:03:04 +08:00
cyclingController.recorderData.DeviceNumber = DeviceNumber;
//显示骑行结果(如果是比赛模式显示比赛最终排名)
if (cyclingModel != CyclingModel.Competition)
{
resultPanel.SetActive(true);
var rs = resultPanel.GetComponent<ResultPanelScript>();
rs.InjectController(this);
rs.SetDataSource(cyclingController.recorderData);
}
cyclingController.recorderData.SaveWithLocalRecordAysnc(cyclingModel, selectParamModel, imageFileName, recordId, path);
2021-04-19 18:03:04 +08:00
}
public byte[] CaptureCamera()
{
return CaptureCameraReturnByte(Camera.main, new Rect(Screen.width * 0f, Screen.height * 0f, Screen.width * 0.5f, Screen.height * 0.5f));
}
private byte[] CaptureCameraReturnByte(Camera camera, Rect rect)
2021-04-19 18:03:04 +08:00
{
// 创建一个RenderTexture对象
RenderTexture rt = new RenderTexture((int)rect.width, (int)rect.height, 0);
// 临时设置相关相机的targetTexture为rt, 并手动渲染相关相机
camera.targetTexture = rt;
camera.Render();
//ps: --- 如果这样加上第二个相机,可以实现只截图某几个指定的相机一起看到的图像。
//ps: camera2.targetTexture = rt;
//ps: camera2.Render();
//ps: -------------------------------------------------------------------
// 激活这个rt, 并从中中读取像素。
RenderTexture.active = rt;
Texture2D screenShot = new Texture2D((int)rect.width, (int)rect.height, TextureFormat.RGB24, false);
screenShot.ReadPixels(rect, 0, 0);// 注这个时候它是从RenderTexture.active中读取像素
screenShot.Apply();
// 重置相关参数以使用camera继续在屏幕上显示
camera.targetTexture = null;
//ps: camera2.targetTexture = null;
RenderTexture.active = null; // JC: added to avoid errors
GameObject.Destroy(rt);
// 最后将这些纹理数据,成一个图片文件
return screenShot.EncodeToJPG();
}
protected void CaptureCamera(Camera camera, Rect rect,string fileName)
{
byte[] bytes = CaptureCameraReturnByte(camera, rect);
//var path = Helper.GetDataDir("MapWorkoutRecords/images");
//string filename = path + "/" + Guid.NewGuid().ToString() + ".png";
System.IO.File.WriteAllBytes(fileName, bytes);
2021-04-19 18:03:04 +08:00
//Debug.Log(string.Format("截屏了一张照片: {0}", filename));
}
public Vector2d GetCenterCoordinate()
{
return coordiantes;
}
public int GetCurrentIndex(double endDistance)
{
int index = 0;
var pointList = mapData.List;
double sumDistance = 0;
if (endDistance >= mapData.TotalDistance)
{
return pointList.Count - 1;
}
for (int i = 0; i < pointList.Count; i++)
{
sumDistance += pointList[i].Distance;
decimal left = (decimal)(endDistance * 1000);
decimal right = (decimal)sumDistance;
if (left <= right)
{
index = i;
break;
}
}
index = endDistance >= mapData.TotalDistance ? pointList.Count - 1 : index;
return index;
}
public Vector2d Along(double endDistance)
{
if (mapData != null)
{
var list = mapData.List.Select(p => new GeoJSON.Net.Geometry.GeographicPosition(p.Point[0], p.Point[1]));
LineString lineString = new LineString(list);
var pt1 = Turf.Along(lineString, endDistance);
var ll = ((GeographicPosition)((GeoJSON.Net.Geometry.Point)pt1.Geometry).Coordinates);
return new Vector2d(ll.Latitude, ll.Longitude);
}
else
{
return new Vector2d(0,0);
}
}
2021-07-09 18:16:50 +08:00
private double CurrentMaxAp = 0;//当前最大AP
public void ComputeMaxAP(double power,int ticks)
2021-03-28 18:17:15 +08:00
{
2021-07-09 18:16:50 +08:00
//计算当前最大AP
if (power > CurrentMaxAp)
2021-03-29 20:32:30 +08:00
{
2021-07-09 18:16:50 +08:00
CurrentMaxAp = power;
}
//分段记录MaxAp
switch (ticks)
{
case 5: recorderData.FiveSecondsMaxAP = CurrentMaxAp; break;
case 10: recorderData.TenSecondsMaxAP = CurrentMaxAp; break;
case 60: recorderData.OneMinuteMaxAP = CurrentMaxAp; break;
case 300: recorderData.FiveMinutesMaxAp = CurrentMaxAp; break;
case 1200: recorderData.TwentyMinutesMaxAP = CurrentMaxAp; break;
default:
break;
2021-03-29 20:32:30 +08:00
}
}
2021-09-02 10:08:46 +08:00
#endregion
}