graph chart引入&骑行结果弹窗

This commit is contained in:
lishuo committed 2021-04-22 19:29:59 +08:00
1 parent 40d118cea3
commit 96f3644b5b
2374 files changed
+485161 -2410

No files matched your search

+10013 -2313
View File
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,195 @@
using ChartAndGraph;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using UnityEngine;
namespace Assets.Scenes.Ride.Scripts
{
public class ChartDataSourceScript:MonoBehaviour, IComparer<DoubleVector2>
{
public string Category = "Player 2";
public int DownSampleToPoints = 100;
List<DoubleVector2> mData = new List<DoubleVector2>(); // the data held by the chart
double pageSize = 2f;
double currentPagePosition = 0.0;
double currentZoom = 0f;
GraphChartBase graph;
double mCurrentPageSizeFactor = double.NegativeInfinity;
private void Start()
{
graph = GetComponent<GraphChartBase>();
}
bool VerifySorted(List<DoubleVector2> data)
{
if (data == null)
return true;
for (int i = 1; i < data.Count; i++)
{
if (data[i].x < data[i - 1].x)
return false;
}
return true;
}
void LoadWithoutDownSampling(int start, int end)
{
for (int i = start; i < end; i++) // load the data
{
graph.DataSource.AddPointToCategory("Player 2", mData[i].x, mData[i].y);
}
}
void LoadWithDownSampling(int start, int end)
{
int total = end - start;
if (DownSampleToPoints >= total)
{
graph.DataSource.HorizontalViewSize = total;
LoadWithoutDownSampling(start, end);
return;
}
double sampleCount = ((double)total) / (double)DownSampleToPoints;
// graph.DataSource.AddPointToCategory(Category, mData[start].x, mData[start].y);
for (int i = 0; i < DownSampleToPoints; i++)
{
int fractionStart = start + (int)(i * sampleCount); // the first point with a fraction
int fractionEnd = start + (int)((i + 1) * sampleCount); // the first point with a fraction
fractionEnd = Math.Min(fractionEnd, mData.Count - 1);
double x = 0, y = 0;
double divide = 0.0;
for (int j = fractionStart; j < fractionEnd; j++) // avarge the poins
{
x += mData[j].x;
y += mData[j].y;
divide++;
}
if (divide > 0.0)
{
x /= divide;
y /= divide;
graph.DataSource.AddPointToCategory("Player 2", x, y);
}
else
Debug.Log("error");
}
// graph.DataSource.AddPointToCategory(Category, mData[last].x, mData[last].y);
}
int FindClosestIndex(double position) // if you want to know what is index is currently displayed . use binary search to find it
{
//NOTE :: this method assumes your data is sorted !!!
int res = mData.BinarySearch(new DoubleVector2(position, 0.0), this);
if (res >= 0)
return res;
return ~res;
}
double PageSizeFactor
{
get
{
return pageSize * graph.DataSource.HorizontalViewSize;
}
}
void findPointsForPage(double position, out int start, out int end) // given a page position , find the right most and left most indices in the data for that page.
{
int index = FindClosestIndex(position); // use binary search to find the closest position to the current scroll point
double endPosition = position + PageSizeFactor;
double startPosition = position - PageSizeFactor;
//starting from the current index , we find the page boundries
for (start = index; start > 0; start--)
{
if (mData[start].x < startPosition) // take the first point that is out of the page. so the graph doesn't break at the edge
break;
}
for (end = index; end < mData.Count; end++)
{
if (mData[end].x > endPosition) // take the first point that is out of the page
break;
}
}
void LoadPage(double pagePosition)
{
if (graph != null)
{
Debug.Log("Loading page :" + pagePosition);
graph.DataSource.StartBatch(); // call start batch
graph.DataSource.HorizontalViewOrigin = 0;
int start, end;
findPointsForPage(pagePosition, out start, out end); // get the page edges
graph.DataSource.ClearCategory("Player 2"); // clear the cateogry
if (DownSampleToPoints <= 0)
LoadWithoutDownSampling(start, end);
else
LoadWithDownSampling(start, end);
graph.DataSource.EndBatch();
graph.HorizontalScrolling = pagePosition;
}
currentPagePosition = pagePosition;
}
public void SetData(List<DoubleVector2> data)
{
if (data == null)
data = new List<DoubleVector2>(); // set up an empty list instead of null
if (VerifySorted(data) == false)
{
Debug.LogWarning("The data used with large data feed must be sorted acoording to the x value, aborting operation");
return;
}
mData = data;
LoadPage(currentPagePosition); // load the page at position 0
}
public void SetDataSource(double[] data)
{
graph = GetComponent<GraphChartBase>();
List<DoubleVector2> source = new List<DoubleVector2>();
for (int i = 0; i < data.Length; i++) // initialize with random data
{
source.Add(new DoubleVector2(i, data[i]));
}
SetData(source);
}
public int Compare(DoubleVector2 x, DoubleVector2 y)
{
if (x.x < y.x)
return -1;
if (x.x > y.x)
return 1;
return 0;
}
public void Update()
{
if (graph != null)
{
//check the scrolling position of the graph. if we are past the view size , load a new page
double pageStartThreshold = currentPagePosition - mCurrentPageSizeFactor;
double pageEndThreshold = currentPagePosition + mCurrentPageSizeFactor - graph.DataSource.HorizontalViewSize;
if (graph.HorizontalScrolling < pageStartThreshold || graph.HorizontalScrolling > pageEndThreshold || currentZoom >= graph.DataSource.HorizontalViewSize * 2f)
{
currentZoom = graph.DataSource.HorizontalViewSize;
mCurrentPageSizeFactor = PageSizeFactor * 0.9f;
LoadPage(graph.HorizontalScrolling);
}
}
}
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: ff4d53c2dc763154da522c9b8cb76877
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
+75 -38
View File
@@ -27,28 +27,32 @@ public class CyclingController : DeviceServiceMonoBase
public int preticks;
#region 参数
private MapRoute mapRoute;//当前路书数据
private MapDataModel mapData;//当前路书数据
private Route route;//当前路书综合数据
public List<MapRouteRanking> mapRouteRankingList;
private Vector2d coordiantes;//当前地图中心
public bool isStart;//当前游戏是否开始
public CyclingModel cyclingModel;//当前骑行模式
public BaseCycling cyclingController { get; set; }
private int RouteId;
private int routeId;
private MapApi mapApi;
private Route mapRoute;
public DateTime startTime;
public DateTime endTime;
public bool isQuit;
public bool isPause;
#endregion
GameObject loadingcanvas;
LoadingController loadingController;
private async Task Login()
{
var result = await new UserApi().Login("13115011550", "laozhong", "");
App.CurrentUser = result.data;
}
GameObject miniMap;
GameObject resultPanel;
void Awake()
{
#if UNITY_EDITOR
@@ -56,34 +60,55 @@ public class CyclingController : DeviceServiceMonoBase
#endif
//获取路书信息
mapApi = ConfigHelper.mapApi;
RouteId = App.RouteIdParam > 0? App.RouteIdParam : 5492;
MapDataModel result = mapApi.GetData(RouteId);
mapRoute = GetNewInstace(RouteId);//获取一个路书所有的数据
MapUDPService.Init();//初始化TCP
if (result != null )
{
Init(result);
}
else
{
Debug.LogError("获取地图数据失败");
}
routeId = App.RouteIdParam > 0? App.RouteIdParam : 5492;
mapRoute = mapApi.GetById(routeId).data;
miniMap = transform.Find("MiniMap").gameObject;//小地图
resultPanel = transform.Find("SingleUI/Panel/ResultPanel").gameObject;
}
private void Start()
{
UIManager.Instance.MainPanel = this.transform.Find("SingleUI/Panel").GetComponent<PFUIPanel>();
UIManager.Instance.ModalsPanel = this.transform.Find("SingleUI/ModalPanel").GetComponent<PFUIPanel>();
loadingController = FindObjectOfType<LoadingController>();
loadingController.InjectController(this);
//开始loading
Init();
}
//加载人物和地图以及UI界面
private void Init(MapDataModel result)
public Texture GetCountryImageByCode(string code)
{
return UIManager.Instance.loginRegOptions.GetCountryImage(code);
}
public Texture GetCountryImageByName(string name)
{
return UIManager.Instance.loginRegOptions.GetCountryImageByName(name);
}
private void Init()
{
loadingController.Init(mapRoute);//初始化loading页面 10
loadingController.AddProcess(10);
MapUDPService.Init();//初始化TCP
loadingController.AddProcess(10);
InitData();//初始化数据
InitGameObject();//初始化场景
}
//初始化数据
private void InitData()
{
mapData = mapApi.GetData(routeId);//获取路书地理数据
route = new Route(mapData, mapRoute);
loadingController.AddProcess(10);
#region 其他场景传参处理
//骑行结果
if (App.routeResult != null )
{
routeResult = App.routeResult;
selectParamModel = App.routeResult.ContinueCyclingParam;
selectParamModel = App.routeResult.ContinueCyclingParam;//继续骑行
preticks = App.routeResult.Ticks;
}
if (selectParamModel == null)
{
selectParamModel = new RouteResultParam
@@ -101,14 +126,30 @@ public class CyclingController : DeviceServiceMonoBase
App.routeResult = null;
mapData = result;
double endDistance = 0;
endDistance = selectParamModel.EndDistance;
coordiantes = Along(endDistance);
#endregion
//计算上次骑行距离调整地图中心点
double endDistance = selectParamModel.EndDistance;
coordiantes = Along(endDistance);
loadingController.AddProcess(10);
//查询排行榜
var list = mapApi.GetRouteRanking(App.RouteIdParam, "1", 0, 10, "");
if (list.result)
{
mapRouteRankingList = list.data.list;
loadingController.CreateRankingList(mapRouteRankingList);
loadingController.AddProcess(10);
}
//异步请求mapbox画出当前路书路线图
//loadingController.DrawMapRoute(mapData);
loadingController.AddProcess(10);
}
//加载人物和地图以及UI界面
private void InitGameObject()
{
map.gameObject.SetActive(true);
player.SetActive(true);
UIObject.SetActive(true);
miniMap.SetActive(true);
}
//设置骑行模式
@@ -119,10 +160,10 @@ public class CyclingController : DeviceServiceMonoBase
switch (cyclingModel)
{
case CyclingModel.Single:
cyclingController = new SingleModel(mapRoute, selectParamModel);
cyclingController = new SingleModel(route, selectParamModel);
break;
case CyclingModel.Review:
cyclingController = new SingleModel(mapRoute, selectParamModel);
cyclingController = new SingleModel(route, selectParamModel);
break;
}
}
@@ -201,13 +242,14 @@ public class CyclingController : DeviceServiceMonoBase
}
public Route GetRoute()
{
return mapRoute;
return route;
}
public MapDataModel GetMapData()
{
return mapData;
}
public void Save(double totalDistance)
{
isStart = false;
@@ -218,7 +260,12 @@ public class CyclingController : DeviceServiceMonoBase
cyclingController.recorderData.AntModelId = AntModelId;
cyclingController.recorderData.ManufacturerId = ManufacturerId;
cyclingController.recorderData.DeviceNumber = DeviceNumber;
cyclingController.recorderData.SaveData(cyclingModel, selectParamModel, imageFileName);
//cyclingController.recorderData.SaveData(cyclingModel, selectParamModel, imageFileName);
//显示骑行结果
resultPanel.SetActive(true);
var rs = resultPanel.GetComponent<ResultPanelScript>();
rs.InjectController(this);
rs.SetDataSource(cyclingController.recorderData);
}
protected string CaptureCamera(Camera camera, Rect rect)
@@ -256,16 +303,6 @@ public class CyclingController : DeviceServiceMonoBase
{
return coordiantes;
}
public Route GetNewInstace(int id)
{
var routeInstance = mapApi.GetById(id);
if (routeInstance == null)
{
return null;
}
var jsonData = mapApi.GetData(RouteId);
return new Route(jsonData, routeInstance.data);
}
public Vector2d Along(double endDistance)
{
if (mapData != null)
+180
View File
@@ -1,9 +1,16 @@
using Assets.Scenes.Ride.Scripts.Model;
using Assets.Scripts;
using Assets.Scripts.Apis.Models;
using System;
using System.Text;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Threading.Tasks;
using UnityEngine;
using UnityEngine.Networking;
namespace Assets.Scenes.Ride.Scripts
{
@@ -167,5 +174,178 @@ namespace Assets.Scenes.Ride.Scripts
}
return value.ToString(CultureInfo.InvariantCulture);
}
/// <summary>
/// Decode google style polyline coordinates.
/// </summary>
/// <param name="encodedPoints"></param>
/// <returns></returns>
private static IEnumerable<CoordinateEntity> Decode(string encodedPoints)
{
if (string.IsNullOrEmpty(encodedPoints))
throw new ArgumentNullException("encodedPoints");
char[] polylineChars = encodedPoints.ToCharArray();
int index = 0;
int currentLat = 0;
int currentLng = 0;
int next5bits;
int sum;
int shifter;
while (index < polylineChars.Length)
{
// calculate next latitude
sum = 0;
shifter = 0;
do
{
next5bits = (int)polylineChars[index++] - 63;
sum |= (next5bits & 31) << shifter;
shifter += 5;
} while (next5bits >= 32 && index < polylineChars.Length);
if (index >= polylineChars.Length)
break;
currentLat += (sum & 1) == 1 ? ~(sum >> 1) : (sum >> 1);
//calculate next longitude
sum = 0;
shifter = 0;
do
{
next5bits = (int)polylineChars[index++] - 63;
sum |= (next5bits & 31) << shifter;
shifter += 5;
} while (next5bits >= 32 && index < polylineChars.Length);
if (index >= polylineChars.Length && next5bits >= 32)
break;
currentLng += (sum & 1) == 1 ? ~(sum >> 1) : (sum >> 1);
yield return new CoordinateEntity
{
Latitude = Convert.ToDouble(currentLat) / 1E5,
Longitude = Convert.ToDouble(currentLng) / 1E5
};
}
}
/// <summary>
/// Encode it
/// </summary>
/// <param name="points"></param>
/// <returns></returns>
private static string Encode(IEnumerable<CoordinateEntity> points)
{
var str = new StringBuilder();
var encodeDiff = (Action<int>)(diff =>
{
int shifted = diff << 1;
if (diff < 0)
shifted = ~shifted;
int rem = shifted;
while (rem >= 0x20)
{
str.Append((char)((0x20 | (rem & 0x1f)) + 63));
rem >>= 5;
}
str.Append((char)(rem + 63));
});
int lastLat = 0;
int lastLng = 0;
foreach (var point in points)
{
int lat = (int)Math.Round(point.Latitude * 1E5);
int lng = (int)Math.Round(point.Longitude * 1E5);
encodeDiff(lat - lastLat);
encodeDiff(lng - lastLng);
lastLat = lat;
lastLng = lng;
}
return str.ToString();
}
public struct CoordinateEntity
{
public double Latitude;
public double Longitude;
public CoordinateEntity(double x, double y) { this.Latitude = x; this.Longitude = y; }
}
public static async Task<byte[]> DownloadImgAsync(List<MapDataModel.Item> list)
{
var result = new List<CoordinateEntity>();
var count = list.Count;
int segement = (int)Math.Ceiling((double)(count / 1000D));
for (int i = 0; i <= count - 1; i++)
{
if (i % segement == 0)
{
result.Add(new CoordinateEntity
{
Latitude = Math.Round(list[i].Point[0], 6),
Longitude = Math.Round(list[i].Point[1], 6),
});
}
}
return await DownloadImgAsync(result);
}
public static async Task<byte[]> DownloadImgAsync(List<CoordinateEntity> list)
{
var polyline = Encode(list);
var encodeline = UnityWebRequest.EscapeURL(polyline); //HttpUtility.UrlEncode(polyline);
//获取封面图片
var url = $"https://api.mapbox.com/styles/v1/mapbox/dark-v10/static/path-4+35ace1-1({encodeline})/auto/1280x1280?access_token={App.MapBoxAccessToken}";
HttpClient c = new HttpClient();
var response = await c.GetAsync(url);
if (response.StatusCode == System.Net.HttpStatusCode.OK)
{
byte[] content = await response.Content.ReadAsByteArrayAsync();
return content;
}
return null;
}
public static string GetMapboxApiUrl(List<MapDataModel.Item> list)
{
var result = new List<CoordinateEntity>();
var count = list.Count;
int segement = (int)Math.Ceiling((double)(count / 1000D));
for (int i = 0; i <= count - 1; i++)
{
if (i % segement == 0)
{
result.Add(new CoordinateEntity
{
Latitude = Math.Round(list[i].Point[0], 6),
Longitude = Math.Round(list[i].Point[1], 6),
});
}
}
var polyline = Encode(result);
var encodeline = UnityWebRequest.EscapeURL(polyline); //HttpUtility.UrlEncode(polyline);
//获取封面图片
var url = $"https://api.mapbox.com/styles/v1/mapbox/dark-v10/static/path-4+35ace1-1({encodeline})/auto/1280x1280?access_token={App.MapBoxAccessToken}";
return url;
}
}
}
@@ -33,12 +33,12 @@ namespace Assets.Scenes.Ride.Scripts
[SerializeField]
GameObject _player;
CyclingController cyclingCotroller;
PlayerController playerController;
public PlayerController playerController;
GameObject _mipMapRoute;
void Start()
{
cyclingCotroller = FindObjectOfType<CyclingController>();
playerController = FindObjectOfType<PlayerController>();
//playerController = FindObjectOfType<PlayerController>();
if (cyclingCotroller != null)
{
var mapdata = cyclingCotroller.GetMapData();
+126 -23
View File
@@ -4,6 +4,10 @@ using UnityEngine.UI;
using Assets.Scripts.Apis;
using System;
using Assets.Scripts;
using Assets.Scripts.Apis.Models;
using System.Collections.Generic;
using UnityEngine.EventSystems;
using UnityEngine.SceneManagement;
namespace Assets.Scenes.Ride.Scripts
{
@@ -11,7 +15,8 @@ namespace Assets.Scenes.Ride.Scripts
//[ExecuteInEditMode]
public class LoadingController : MonoBehaviour
{
Text mapName;
#region GameObject
Text mapName;
AbstractMap _map;
Text level;
Text distance;
@@ -19,20 +24,87 @@ namespace Assets.Scenes.Ride.Scripts
Text slope;
Text rideNum;
Text uploadByUserName;
Text processText;
Text mapDescText;
RawImage head;
RawImage country;
RawImage mapCountry;
RawImage mapRouteImage;
RawImage altitudeGraph;
Button rideNow;
Button cancel;
MapApi mapApi;
GameObject panel;
CanvasGroup canvasGroup;
GameObject loadingPanel;
private void Start()
{
int routeId = App.RouteIdParam >0? App.RouteIdParam : 5492;
mapApi = new MapApi();
Transform mapRanking;
Slider slider;
#endregion
#region 属性
float process = 0;//0-100 %
#endregion
CyclingController cyclingController;
private void Start()
{
//InitGameObject();
}
public void InjectController(CyclingController controller)
{
cyclingController = controller;
}
//提供给主控制器初始化用
public void Init(MapRoute route)
{
InitGameObject();
InitGameObjectData(route);
}
//展示当前路书图片
public void SetMapRouteImage(string url)
{
Utils.DisplayImage(StartCoroutine, mapRouteImage, url);
}
public void DrawMapRoute(MapDataModel mapData)
{
var url = Helper.GetMapboxApiUrl(mapData.List);
//Utils.DisplayImage(StartCoroutine, mapRouteImage, url);
}
//设定当前loading进度
public void AddProcess(float v)
{
process += v;
slider.value = process;
slider.onValueChanged.AddListener((f) =>
{
processText.text = $"{(f ).ToString("#0")}%";
});
if (process == 100)
{
rideNow.interactable = true;
rideNow.enabled = true;
}
}
//创建排行榜
public void CreateRankingList(List<MapRouteRanking> list)
{
var prefab = Resources.Load<GameObject>("UI/Prefab/Ride/RankingItem");
var parent = transform.Find("Panel/MapRanking");
foreach (var item in list)
{
GameObject newObj = (GameObject)Instantiate(prefab, parent);
var selectPlayerItemScript = newObj.GetComponent<RankingItemScript>();
selectPlayerItemScript.SetRanking(item.RowNumber.ToString());
selectPlayerItemScript.SetName(item.NickName);
selectPlayerItemScript.SetTimer(item.IsDNF?"DNF":item.TotalTime);
selectPlayerItemScript.SetHead(item.WxHeadImg);
var texture = cyclingController.GetCountryImageByCode(item.CountryCode);
selectPlayerItemScript.SetCountry(texture);
}
}
private void InitGameObject()
{
panel = transform.Find("Panel").gameObject;
mapName = transform.Find("Panel/MapName").GetComponent<Text>();
loadingPanel = transform.Find("Panel/LoadingAnimation").gameObject;
distance = transform.Find("Panel/Distance").GetComponent<Text>();
level = transform.Find("Panel/level/Text").GetComponent<Text>();
elevaction = transform.Find("Panel/Elevaction").GetComponent<Text>();
@@ -40,34 +112,67 @@ namespace Assets.Scenes.Ride.Scripts
rideNum = transform.Find("Panel/RideNum").GetComponent<Text>();
uploadByUserName = transform.Find("Panel/UploadByUserName").GetComponent<Text>();
country = transform.Find("Panel/UploadByCountry").GetComponent<RawImage>();
mapCountry = transform.Find("Panel/Country").GetComponent<RawImage>();
head = transform.Find("Panel/UploadByHead").GetComponent<RawImage>();
mapRouteImage = transform.Find("Panel/MapRouteImage").GetComponent<RawImage>();
altitudeGraph = transform.Find("Panel/AltitudeGraph").GetComponent<RawImage>();
mapRanking = transform.Find("Panel/MapRanking");
slider = transform.Find("Panel/Process").GetComponent<Slider>();
processText = transform.Find("Panel/ProcessText").GetComponent<Text>();
mapDescText = transform.Find("Panel/MapDesc").GetComponent<Text>();
rideNow = transform.Find("Panel/RideNow").GetComponent<Button>();
cancel = transform.Find("Panel/Cancel").GetComponent<Button>();
var root = transform.parent;
_map = root.Find("Map").GetComponent<AbstractMap>();
canvasGroup = transform.GetComponent<CanvasGroup>();
rideNow.enabled = false;
rideNow.interactable = false;
UIManager.AddEvent(rideNow.gameObject, UnityEngine.EventSystems.EventTriggerType.PointerClick, StartRide);
UIManager.AddEvent(cancel.gameObject, UnityEngine.EventSystems.EventTriggerType.PointerClick, Cancel);
if (routeId > 0)
}
void StartRide(BaseEventData baseEvent)
{
//启用ridenow
canvasGroup.blocksRaycasts = false;
depressFlag = true;
}
void Cancel(BaseEventData baseEvent)
{
SceneManager.LoadScene("MainScene");
}
private void InitGameObjectData(MapRoute route)
{
if (route != null)
{
var map = mapApi.GetById(routeId);
var route = map.data;
#region 绑定路书基本信息
mapName.text = route.Name;
level.text = route.Hard;
elevaction.text = Math.Round(route.EleDifference,0).ToString()+"FT";
slope.text = Math.Round(route.AverageGrade,2).ToString() + "%";
elevaction.text = Math.Round(route.EleDifference, 0).ToString() + "M";
slope.text = Math.Round(route.AverageGrade, 2).ToString() + "%";
rideNum.text = route.TheHeat.ToString();
distance.text = route.Distance.ToString("f1")+"KM";
var userList = mapApi.GetOnlineUserInfo(new int[] { route.UserId }).data;
distance.text = route.Distance.ToString("f1") + "KM";
mapDescText.text = route.Dec;
var userList = ConfigHelper.mapApi.GetOnlineUserInfo(new int[] { route.UserId }).data;
if (userList.Count > 0)
{
uploadByUserName.text = userList[0].Name;
var countryUrl = App.Host + $"User/GetCountryImg?userid={userList[0].Id}";
Utils.DisplayImage(StartCoroutine, head, userList[0].HeadImage);
Utils.DisplayImage(StartCoroutine, country, countryUrl);
}
Utils.DisplayImage(StartCoroutine, head, userList[0].HeadImage);//头像
country.texture = cyclingController.GetCountryImageByCode(route.CountryCode);//上传者国家
mapCountry.texture = cyclingController.GetCountryImageByName(userList[0].Country);//路书国家
Utils.DisplayImage(StartCoroutine, altitudeGraph, route.AltitudeGraph);//海拔图
}
#endregion
#region 地图注册 排行榜等接口
_map.OnInitialized += _map_OnInitialized;
_map.OnEditorPreviewEnabled += OnEditorPreviewEnabled;
_map.OnEditorPreviewDisabled += OnEditorPreviewDisabled;
#endregion
}
}
@@ -78,19 +183,18 @@ namespace Assets.Scenes.Ride.Scripts
{
if (s == ModuleState.Finished)
{
canvasGroup.blocksRaycasts = false;
depressFlag = true;
AddProcess(40);
}
};
}
void OnEditorPreviewEnabled()
{
transform.gameObject.SetActive(false);
//transform.gameObject.SetActive(false);
}
void OnEditorPreviewDisabled()
{
transform.gameObject.SetActive(true);
//transform.gameObject.SetActive(true);
}
public float targetAlpha = 0f;
public float alphaSpeed = 2.0f;
@@ -112,7 +216,6 @@ namespace Assets.Scenes.Ride.Scripts
if (canvasGroup.alpha == 0)
{
transform.gameObject.SetActive(false);
loadingPanel.SetActive(false);
}
}
}
@@ -521,6 +521,8 @@ namespace Assets.Scenes.Ride.Scripts.Model
return (DateTime.Now - LastActiveTime).TotalSeconds > 3;
}
}
public string Country { get; set; }
}
public class KeyPaire
@@ -30,6 +30,8 @@ namespace Assets.Scenes.Ride.Scripts.Model
/// </summary>
public double _Lon { get; set; } = 0d;
public double _TotalClimb { get; set; } = 0d;
//public double _Bearing = 0d;
public TargetData Clone()
@@ -52,7 +52,8 @@ namespace Assets.Scenes.Ride.Scripts
_Cadence = cadance,
_HeartRate = heartRate,
_Lat = currentlatlong.x,
_Lon = currentlatlong.y
_Lon = currentlatlong.y,
_TotalClimb = totalClimb,
};
recorderData.RiderDatas.Add(targetData);
@@ -64,11 +65,12 @@ namespace Assets.Scenes.Ride.Scripts
mainController.cyclingController.Run(null);
}
}
//上传数据
public override void Upload()
{
mainController.Save(TotalDistance);
SceneManager.LoadScene("MainScene");
//SceneManager.LoadScene("MainScene");
}
#endregion
}
@@ -0,0 +1,51 @@
using Assets.Scripts;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using UnityEngine;
using UnityEngine.UI;
namespace Assets.Scenes.Ride.Scripts
{
public class RankingItemScript:MonoBehaviour
{
Text rankingText;
Text nameText;
Text timerText;
RawImage head;
RawImage country;
private void Awake()
{
rankingText = transform.Find("Ranking").GetComponent<Text>();
nameText = transform.Find("Name").GetComponent<Text>();
timerText = transform.Find("Timer").GetComponent<Text>();
head = transform.Find("Head").GetComponent<RawImage>();
country = transform.Find("Country").GetComponent<RawImage>();
}
public void SetRanking(string ranking)
{
rankingText.text = ranking.PadLeft(2,'0');
}
public void SetName(string name)
{
nameText.text = name;
}
public void SetTimer(string timer)
{
timerText.text = timer;
}
public void SetHead(string url)
{
Utils.DisplayImage(StartCoroutine, head, url);
}
public void SetCountry(Texture texture)
{
country.texture = texture;
}
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: f48cdbeff59981140b430d66a9c53fc6
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,98 @@
using Assets.Scenes.Ride.Scripts.Model;
using Assets.Scripts;
using Assets.Scripts.Apis.Models;
using UnityEngine;
using UnityEngine.UI;
using System.Linq;
using System;
namespace Assets.Scenes.Ride.Scripts
{
public class ResultPanelScript:MonoBehaviour
{
#region 路书信息
Text date;
Text time;
Text level;
Text mapName;
Text distance;
RawImage country;
RawImage altudeGraph;
#endregion
#region 骑行结果
Text rideTime;
Text rideDistance;
Text totalClimbed;
Text wkgText;
Text avCadence;
Text avHeatrate;
Text maxPower;
Text avPower;
Text maxSpeed;
Text avSpeed;
#endregion
CyclingController cyclingController;
private void Awake()
{
#region 路书信息
date = transform.Find("MapPanel/Date").GetComponent<Text>();
time = transform.Find("MapPanel/Timer").GetComponent<Text>();
level = transform.Find("MapPanel/Level/Text").GetComponent<Text>();
mapName = transform.Find("MapPanel/MapName").GetComponent<Text>();
distance = transform.Find("MapPanel/Distance").GetComponent<Text>();
country = transform.Find("MapPanel/Country").GetComponent<RawImage>();
altudeGraph = transform.Find("MapPanel/AltudeGraph").GetComponent<RawImage>();
#endregion
#region 骑行记录
rideTime = transform.Find("TimePanel/Timer").GetComponent<Text>();
rideDistance = transform.Find("DistancePanel/Distance").GetComponent<Text>();
totalClimbed = transform.Find("FitPanel/TotalClimbedView/Value").GetComponent<Text>();
wkgText = transform.Find("FitPanel/FTPView/Value").GetComponent<Text>();
avCadence = transform.Find("FitPanel/CadenceView/Value").GetComponent<Text>();
avHeatrate = transform.Find("FitPanel/HeartView/Value").GetComponent<Text>();
maxPower = transform.Find("FitPanel/MaxPowerView/Value").GetComponent<Text>();
avPower = transform.Find("FitPanel/AveragePowerView/Value").GetComponent<Text>();
maxSpeed = transform.Find("FitPanel/MaxSpeedView/Value").GetComponent<Text>();
avSpeed = transform.Find("FitPanel/AverageSpeed/Value").GetComponent<Text>();
#endregion
}
public void InjectController(CyclingController controller)
{
cyclingController = controller;
}
public void RegisterButton()
{
}
public void SetDataSource(RecorderDataModel record)
{
var route = record.CurrentRoute.RouteInstance;
//绑定路书信息
var dateString = record.StartTime.ToString();
date.text = dateString.Split(' ')[0];
time.text = dateString.Split(' ')[1];
level.text = route.Hard;
mapName.text = route.Name;
distance.text = route.Distance.ToString("f1")+"KM";
country.texture = cyclingController.GetCountryImageByCode(route.CountryCode);
Utils.DisplayImage(StartCoroutine, altudeGraph, route.AltitudeGraph);
//绑定骑行记录结果
rideTime.text = Helper.FormatTicks(record.RiderDatas.Count);
rideDistance.text = record.RiderDatas.Last()._Distance.ToString("f1")+"KM";
totalClimbed.text = record.RiderDatas.Last()._TotalClimb.ToString("f1");
var power = Math.Round(record.RiderDatas.Average(c => c._Power),0);
avPower.text = power.ToString();
maxPower.text = record.RiderDatas.Max(c => c._Power).ToString("g0");
avHeatrate.text = record.RiderDatas.Average(c => c._HeartRate.GetValueOrDefault(0)).ToString("g0");
avSpeed.text = record.RiderDatas.Average(c => c._Speed).ToString("f1");
maxSpeed.text = record.RiderDatas.Max(c => c._Speed).ToString("f1");
wkgText.text = Math.Round(power / record.CurrentUser.Weight,2).ToString();
}
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: ef1e97118bc5de7448476f593e83d251
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -66,11 +66,11 @@ namespace Assets.Scenes.Ride.Scripts
}
PlayerController playerController;
public PlayerController playerController;
public void Start()
{
cyclingCotroller = transform.parent.GetComponent<CyclingController>();
playerController = FindObjectOfType<PlayerController>();
//playerController = FindObjectOfType<PlayerController>();
_map.OnTileFinished += _map_OnTileFinished;
StartCoroutine(QueryTimer());
//CreateRoute();
@@ -99,7 +99,7 @@ namespace Assets.Scenes.Ride.Scripts
var path = new List<Vector3>();
var mapData = cyclingCotroller.GetMapData();
if (mapData != null)
if (mapData != null && playerController != null)
{
//foreach (var mapDataItem in mapData.List)
for (int i = 0; i < mapData.List.Count; i++)
@@ -27,7 +27,7 @@ namespace Assets.Scenes.Ride.Scripts
GameObject reviewPanel;
InputField inputField;
private int pageIndex = 0;
private int pageSize = 8;
private int pageSize = 10;
private int totalPages = 0;
private string seachName = string.Empty;
CyclingController cyclingController;
@@ -117,16 +117,19 @@ namespace Assets.Scenes.Ride.Scripts
}
private void Start()
{
Refresh();
CreateGameObject(cyclingController.mapRouteRankingList);
}
private void Refresh()
{
var list = mapApi.GetRouteRanking(App.RouteIdParam, "1", pageIndex, pageSize, seachName);
totalPages = list.data.TotalPages;
CreateGameObject(list.data.list);
}
private void CreateGameObject(List<MapRouteRanking> list)
{
var parent = transform.Find("Panel/PlayerList/Scroll View/Viewport/Content");
foreach (var item in list.data.list)
foreach (var item in list)
{
GameObject newObj = (GameObject)Instantiate(prefab, parent);
var selectPlayerItemScript = newObj.GetComponent<SelectPlayerItemScript>();
+71 -22
View File
@@ -143,8 +143,12 @@ namespace Assets.Scenes.Ride.Scripts
UIManager.AddEvent(cancelQuitButton.gameObject, UnityEngine.EventSystems.EventTriggerType.PointerClick, CancelQuit);
UIManager.AddEvent(closeQuitButton.gameObject, UnityEngine.EventSystems.EventTriggerType.PointerClick, CloseQuit);
UIManager.AddEvent(viewButton.gameObject, UnityEngine.EventSystems.EventTriggerType.PointerClick, ChangeView);
UIManager.AddEvent(singleButton.gameObject, UnityEngine.EventSystems.EventTriggerType.PointerEnter, OnPointEnter);
UIManager.AddEvent(shadowButton.gameObject, UnityEngine.EventSystems.EventTriggerType.PointerEnter, OnPointEnter);
UIManager.AddEvent(singleButton.gameObject, UnityEngine.EventSystems.EventTriggerType.PointerExit, OnPointExit);
UIManager.AddEvent(shadowButton.gameObject, UnityEngine.EventSystems.EventTriggerType.PointerExit, OnPointExit);
//startBtn.onClick.AddListener(StartRide);
//simpleBtn.onClick.AddListener(ClearPanel);
//pauseButton.onClick.AddListener(PauseRide);
@@ -160,6 +164,29 @@ namespace Assets.Scenes.Ride.Scripts
#endregion
}
float? localY;
void OnPointEnter(BaseEventData pointerEventData)
{
var button = ((PointerEventData)pointerEventData).pointerEnter.GetComponent<Button>();
if (button != null)
{
var enterTransform = button.transform;
if (localY == null)
{
localY = enterTransform.localPosition.y;
}
enterTransform.DOLocalMoveY(localY.Value + 5f, 0.5f);
}
}
void OnPointExit(BaseEventData pointerEventData)
{
var button =((PointerEventData)pointerEventData).pointerEnter.GetComponent<Button>();
if (button != null)
{
var enterTransform = button.transform;
enterTransform.DOLocalMoveY(localY.Value, 0.5f);
}
}
void Start()
{
playerController = FindObjectOfType<PlayerController>();
@@ -293,13 +320,16 @@ namespace Assets.Scenes.Ride.Scripts
}
private void SaveRide(BaseEventData baseEventData)
{
mainController.SetQuit();
if (playerController.TotalTicks > 0 && !mainController.isQuit )
{
mainController.SetQuit();
playerController.Upload();
quitPanel.SetActive(false);
}
SceneManager.LoadScene("MainScene");
else
{
SceneManager.LoadScene("MainScene");
}
}
private void CancelQuit(BaseEventData baseEventData)
{
@@ -367,35 +397,54 @@ namespace Assets.Scenes.Ride.Scripts
//初始化海拔图
void RenderChart()
{
elevationChart.ClearData();
elevationList = mainController.GetLineChartData();
totalCount = elevationList.Length;
maxCacheDataNumber = Math.Min(totalCount, maxCacheDataNumber);
elevationChart.SetMaxCache(maxCacheDataNumber);
//elevationChart.ClearData();
//elevationList = mainController.GetLineChartData();
//totalCount = elevationList.Length;
//maxCacheDataNumber = Math.Min(totalCount, maxCacheDataNumber);
//elevationChart.SetMaxCache(maxCacheDataNumber);
////for (int i = 0; i < maxCacheDataNumber; i++)
////{
//// elevationChart.AddData(0, elevationList[i]);
////}
////elevationChart.RefreshChart();
//ElevationToScreenPoint();
//var endIndex = playerController.CurrentIndex;
//var s = endIndex / maxCacheDataNumber;
//var v = endIndex % maxCacheDataNumber;
//maxCacheDataNumber = Math.Min(totalCount-s* maxCacheDataNumber, maxCacheDataNumber);
//for (int i = 0; i < maxCacheDataNumber; i++)
//{
// elevationChart.AddData(0, elevationList[i]);
// initCount++;
// if (initCount > maxCacheDataNumber) break;
// AddOneData(s * maxCacheDataNumber + v + i);
//}
//elevationChart.RefreshChart();
ElevationToScreenPoint();
var endIndex = playerController.CurrentIndex;
var s = endIndex / maxCacheDataNumber;
var v = endIndex % maxCacheDataNumber;
maxCacheDataNumber = Math.Min(totalCount-s* maxCacheDataNumber, maxCacheDataNumber);
for (int i = 0; i < maxCacheDataNumber; i++)
//elevationChart.RefreshChart();
var mapData = mainController.GetMapData();
double x = 0;
Dictionary<double, double> dataSource = new Dictionary<double, double>();
List<double> dd = new List<double>();
var one = mapData.List.Where(c => c.Distance == 0).Count();
foreach (var item in mapData.List)
{
initCount++;
if (initCount > maxCacheDataNumber) break;
AddOneData(s * maxCacheDataNumber + v + i);
x += item.Distance;
if (!dataSource.ContainsKey(x))
{
dataSource.Add(x, item.Elevation);
}
dd.Add(item.Elevation);
}
elevationChart.RefreshChart();
var sc = transform.Find("Panel/GraphChart").GetComponent<ChartDataSourceScript>();
sc.SetDataSource(dd.ToArray());
if (App.CurrentUser != null)
{
Utils.DisplayImage(StartCoroutine, img, App.CurrentUser.WxHeadImg);
}
}
//长路线动态更新chart
private int initCount;
+1 -1
View File
@@ -12,7 +12,7 @@ namespace Assets.Scenes.Ride.Scripts
var appVersion = transform.GetComponent<Text>();
if (appVersion != null)
{
appVersion.text = App.AppVersion;
appVersion.text = "V"+App.AppVersion;
}
}
}