using System;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Networking;
using UnityEngine.UI;
public class Player : NetworkBehaviour
{
public float speed = 2;
Transform look;
NetworkIdentity view;
Rigidbody rb;
float inpX, inpY, oldF;
double ping;
// Use this for initialization
void Start()
{
rb = GetComponent<Rigidbody>();
view = GetComponent<NetworkIdentity>();
look = GameObject.FindWithTag("MainCamera").transform;
if (view.isLocalPlayer) tag = "Player";
fps = GameObject.Find("FPS Text").GetComponent<Text>();
}
void Update()
{
if (view.isLocalPlayer)
{
inpY = Input.GetAxis("Vertical");
inpX = Input.GetAxis("Horizontal");
CmdGetInputs(new Vector2(inpX, inpY), DateTime.UtcNow.ToFileTimeUtc());//отправляем управление серверу
}
//получаем позицию, скорость, повороты и время отправки
if (view.isServer) RpcGetRB(transform.position, transform.eulerAngles, rb.velocity, rb.angularVelocity, DateTime.UtcNow.ToFileTimeUtc());
if (Time.time - oldF > 0.5f || oldF == 0)
{
oldF = Time.time;
fps.text = (int)(1 / Time.deltaTime) + " fps. " + Math.Round(ping, 5) + " ms.";
}
}
// Update is called once per frame
void FixedUpdate()
{
if (view.isServer)
{
Vector3 v = rb.velocity;
rb.velocity = Vector3.forward * Time.deltaTime * 10 * speed * inpY
+ Vector3.right * Time.deltaTime * 10 * speed * inpX;
rb.velocity = new Vector3(rb.velocity.x, v.y, rb.velocity.z);
}
else {
if (Vector3.Distance(transform.position, Pos) > 0.05f)
transform.Translate((Pos - transform.position).normalized * Time.deltaTime, Space.World);
if (Vector3.Distance(transform.eulerAngles, Rot) > 0.1f)
transform.eulerAngles = Vector3.Slerp(transform.eulerAngles, Rot, Time.deltaTime);
}
}
float ol;
[Command]
void CmdGetInputs(Vector2 inp, long time)
{
if (view.isLocalPlayer && view.isServer) return;
inpX = inp.x;
inpY = inp.y;
if (ol == 0 || Time.time - ol > 1)
{
ol = Time.time;
print("Ping: " + Math.Round((DateTime.UtcNow - DateTime.FromFileTimeUtc(time)).TotalMilliseconds));
}
}
Vector3 Pos, Rot;
Text fps;
[ClientRpc]
void RpcGetRB(Vector3 pos, Vector3 rot, Vector3 vel, Vector3 rotvel, long time)
{
if (view == null || rb == null || view.isServer) return;
ping = Math.Round((DateTime.UtcNow - DateTime.FromFileTimeUtc(time)).TotalMilliseconds);
Pos = pos;
Rot = rot;
rb.velocity = vel;
rb.angularVelocity = rotvel;
}
}