57 lines
1.8 KiB
C#
57 lines
1.8 KiB
C#
using GTANetworkAPI;
|
|
using ReallifeGamemode.Server.Entities;
|
|
using ReallifeGamemode.Server.Managers;
|
|
using ReallifeGamemode.Server.Models;
|
|
using System;
|
|
using System.Collections.Generic;
|
|
using System.Text;
|
|
|
|
namespace ReallifeGamemode.Server.Events
|
|
{
|
|
class Update : Script
|
|
{
|
|
private Dictionary<NetHandle, Vector3> lastPositions = new Dictionary<NetHandle, Vector3>();
|
|
private DateTime lastSave = DateTime.UtcNow;
|
|
|
|
[ServerEvent(Event.Update)]
|
|
void UpdateEvent()
|
|
{
|
|
NAPI.Pools.GetAllVehicles().ForEach(v =>
|
|
{
|
|
Vector3 lastPosition = v.Position;
|
|
if (lastPositions.ContainsKey(v.Handle)) lastPosition = lastPositions[v.Handle];
|
|
|
|
double distanceDriven = v.HasSharedData("drivenDistance") ? v.GetSharedData("drivenDistance") : 0;
|
|
|
|
distanceDriven += (lastPosition.DistanceTo(v.Position) / 1000.0);
|
|
|
|
v.SetSharedData("drivenDistance", (float)distanceDriven);
|
|
|
|
lastPositions[v.Handle] = v.Position;
|
|
});
|
|
|
|
if (DateTime.UtcNow.Subtract(lastSave).Seconds >= 30)
|
|
{
|
|
lastSave = DateTime.UtcNow;
|
|
// save to db
|
|
using (var dbContext = new DatabaseContext())
|
|
{
|
|
foreach(var key in lastPositions.Keys)
|
|
{
|
|
Vehicle v = key.Entity<Vehicle>();
|
|
if (!v.HasSharedData("drivenDistance")) continue;
|
|
|
|
ServerVehicle sVeh = VehicleManager.GetServerVehicleFromVehicle(v, dbContext);
|
|
|
|
if (sVeh == null) continue;
|
|
|
|
sVeh.DistanceDriven = (float)v.GetSharedData("drivenDistance");
|
|
|
|
}
|
|
dbContext.SaveChanges();
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|