Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Collections;
- using System.Collections.Generic;
- using UnityEngine;
- using GalaxyLib;
- using UnityEngine.Events;
- using System.Reflection;
- using System.Linq;
- public class UnitController : Unit
- {
- #region Компоненты
- [HideInInspector]
- public GalaxyNetID netId;
- //private CharacterController characterController;
- private Animator animator;
- #endregion
- #region Здоровье
- public override float Health
- {
- get { return health; }
- set
- {
- base.Health = value;
- if (initUnit != InitUnit.Local)
- return;
- netId.CallRPC("RpcSyncHealth", value);
- }
- }
- #endregion
- #region NetVar Для синхронизации анимации движения
- [HideInInspector]
- [NetVar]
- public float _motionX;
- [HideInInspector]
- [NetVar]
- public int _motionY;
- [HideInInspector]
- [NetVar]
- public float _motionZ;
- [HideInInspector]
- [NetVar]
- public float _lookDirectionX;
- [HideInInspector]
- [NetVar]
- public float _lookDirectionY;
- [HideInInspector]
- [NetVar]
- public float _lookDirectionZ;
- [HideInInspector]
- [NetVar]
- public bool _unitOff;
- [HideInInspector]
- [NetVar]
- public string _unitName;
- #endregion
- #region Список всех дочерних модулей
- [SerializeField]
- private List<ModulBase> moduls;
- #endregion
- #region Список действий
- public List<UnitAction> actions = new List<UnitAction>();
- #endregion
- Vector3 moveDirection;//Вектор движения
- #region Debug
- Vector3 dbMotion;
- Vector3 dbLookDirection;
- #endregion
- protected void Start()
- {
- netId = GetComponent<GalaxyNetID>();
- animator = GetComponent<Animator>();
- tag = "Unit";
- gameObject.layer = 9;
- Invoke("ConnectToNet", 1);
- }
- private void ConnectToNet()
- {
- if (!netId.inited)
- {
- Invoke("ConnectToNet", 1);
- return;
- }
- if (netId.isMy)
- {
- initUnit = InitUnit.Local;
- #region Создаем элементы действий
- UnitAction action = new UnitAction("Enable Unit");
- action.OnUnitAction.AddListener(EnableBot);
- actions.Add(action);
- action = new UnitAction("Disable Unit");
- action.OnUnitAction.AddListener(DisableBot);
- actions.Add(action);
- action = new UnitAction("Destroy Unit");
- action.OnUnitAction.AddListener(SelfDestroyBot);
- actions.Add(action);
- #endregion
- #region Имя юнита
- _unitName = GalaxyNetwork.Connection.clientNikName;
- OnNetEvent("UnitName");
- #endregion
- _unitOff = animator.GetBool("Off");
- }
- else
- {
- initUnit = InitUnit.NetClient;
- }
- Invoke("Initialise", 1);
- }
- private void Initialise()
- {
- AddModuls();
- if (initUnit == InitUnit.NetClient)
- {
- name = _unitName + " Client";
- OnNetEvent("UnitName");
- animator.applyRootMotion = false;
- netId.CallRPC("RpcGetHealth");
- SyncModulStatus();
- }
- if (initUnit == InitUnit.Local)
- {
- name = _unitName + " Local";
- }
- GameEvents.Singleton.OnEventInitUnit(gameObject, netId.isMy);
- }
- public override void GetUnitName(MessageArgsString args)
- {
- args.stringArg = _unitName;
- }
- public bool LocalUnit
- {
- get
- {
- return netId.isMy;
- }
- }
- private void SyncModulStatus()
- {
- foreach (ModulBase modul in moduls)
- {
- }
- }
- protected void Update()
- {
- if (initUnit == InitUnit.Local)
- {
- GetInput();
- if (_unitOff == true)
- return;
- //Получаем направление взгляда из модуля оптики
- Vector3 dir = Vector3.zero;
- foreach (ModulBase modul in moduls)
- {
- if (modul is IGetLookDirection)
- {
- dir = (modul as IGetLookDirection).GetDirection();
- break;
- }
- }
- //Назначаем направление взгляда
- SetLookDirection(dir);
- //SetLookDirection(CameraController.Singleton.hitForwardCollision.point);
- #region Сохраняем координаты точки в пространстве в переменные lookDirection для их синхронизации по сети
- if (dbLookDirection != dir)
- {
- dbLookDirection = dir;
- OnNetEvent("LookDirection");
- }
- _lookDirectionX = dir.x;
- _lookDirectionY = dir.y;
- _lookDirectionZ = dir.z;
- #endregion
- #region Сохраняем данные аниматора для их синхронизации по сети
- Vector3 tmp = new Vector3(animator.GetFloat("Side"), animator.GetInteger("Straif"), animator.GetFloat("Front"));
- if(dbMotion != tmp)
- {
- dbMotion = tmp;
- OnNetEvent("Motion");
- }
- _motionZ = animator.GetFloat("Front");
- _motionX = animator.GetFloat("Side");
- _motionY = animator.GetInteger("Straif");
- #endregion
- }
- if (initUnit == InitUnit.NetClient)
- {
- //Если не нашь, то для назначения направления взгляда используем синхронизируемые переменные lookDirection
- Vector3 tmp = new Vector3(_lookDirectionX, _lookDirectionY, _lookDirectionZ);
- if (dbLookDirection != tmp)
- {
- dbLookDirection = tmp;
- OnNetEvent("LookDirection");
- }
- SetLookDirection(new Vector3(_lookDirectionX, _lookDirectionY, _lookDirectionZ));
- #region Синхронизируем аниматор
- animator.SetBool("Off", _unitOff);
- tmp = new Vector3(_motionX, _motionY, _motionZ);
- if (dbMotion != tmp)
- {
- dbMotion = tmp;
- OnNetEvent("Motion");
- }
- animator.SetInteger("Straif", _motionY);
- animator.SetFloat("Front", _motionZ);//, 0.1f, Time.deltaTime);
- animator.SetFloat("Side", _motionX);//, 0.1f, Time.deltaTime);
- #endregion
- #region Синхронизируем имя юнита
- if (name != _unitName)
- {
- name = _unitName;
- }
- #endregion
- }
- }
- protected void FixedUpdate()
- {
- SetMove(moveDirection);
- }
- #region Действия робота
- private void SetMove(Vector3 moveDirection)
- {
- if (initUnit != InitUnit.Local)
- return;
- foreach (ModulBase modul in moduls)
- {
- if (modul is ISetMoveDirection)
- {
- (modul as ISetMoveDirection).SetDirection(moveDirection);
- }
- }
- }
- private void SetLookDirection(Vector3 value)
- {
- #region Сообщаем модулям точку в пространстве, куда нужно смотреть
- foreach (ModulBase modul in moduls)
- {
- if (modul is ISetLookDirection)
- {
- (modul as ISetLookDirection).SetDirection(value);
- }
- }
- #endregion
- }
- private void Shoot()
- {
- foreach (ModulBase modul in moduls)
- {
- if (modul is IShoot)
- {
- bool shoot = false;
- (modul as IShoot).Shoot(out shoot);
- if(shoot == true)
- {
- netId.CallRPC("RpcShoot", moduls.IndexOf(modul));
- }
- }
- }
- }
- private void SelfDestroyBot()
- {
- Health = 0;
- }
- #endregion
- private void GetInput()
- {
- moveDirection = Vector3.zero;
- if (Cursor.visible == false)
- {
- moveDirection += PlayerInput.Singletone.input;
- moveDirection = new Vector3(moveDirection.x, -moveDirection.y, moveDirection.z);//Инвертируем стрейф
- if (CustomInput.Singleton.GetButtonDown("Mouse0"))
- {
- Shoot();
- }
- if (CustomInput.Singleton.GetButtonDown("Mouse1"))
- {
- foreach (ModulBase modul in moduls)
- {
- if (modul is IOpticCamera)
- {
- (modul as IOpticCamera).EnableCamera();
- }
- }
- }
- if (CustomInput.Singleton.GetButton("Weapon2"))
- {
- Health -= 1;
- }
- if (CustomInput.Singleton.GetButton("Weapon3"))
- {
- Health += 1;
- }
- }
- }
- #region События
- #region События Аниматора Вкл/Откл робота
- public void UnitEnable()
- {
- if (initUnit == InitUnit.Local)
- {
- EnableAllModul();
- }
- }
- public void UnitDisable()
- {
- if (initUnit == InitUnit.Local)
- {
- DisableAllModul();
- }
- }
- #endregion
- #region Подписанное Событие Вкл/Откл робота
- protected override void EnableBot()
- {
- animator.SetBool("Off", false);
- _unitOff = false;
- }
- protected override void DisableBot()
- {
- animator.SetBool("Off", true);
- _unitOff = true;
- }
- #endregion
- protected override void DestroyBot()
- {
- base.DestroyBot();
- foreach (ModulBase modul in moduls)
- {
- modul.ModulDestroy();
- }
- }
- #region Добавляем модули в массив
- private void RecheckModuls()
- {
- DisableBot();
- Invoke("AddModuls", 1);
- }
- private void AddModuls()
- {
- moduls = new List<ModulBase>();
- foreach (var item in GetComponentsInChildren<ModulBase>())
- {
- moduls.Add(item);
- item.UnitInitialise(this);
- }
- }
- #endregion
- #region Вкл/Откл всех модулей
- //Вкл. все модули
- private void EnableAllModul()
- {
- foreach (ModulBase modul in moduls)
- {
- modul.ModulEnable();
- }
- }
- //Вкл. все модули
- private void DisableAllModul()
- {
- foreach (ModulBase modul in moduls)
- {
- modul.ModulDisable();
- }
- }
- #endregion
- #endregion
- void GetUnitActions(MessageArgsActions args)
- {
- args.actions = actions;
- }
- #region Обмен данными робота
- [NetRPC]
- public void RpcSyncHealth(float value)
- {
- OnNetEvent("RpcSyncHealth");
- if (initUnit != InitUnit.NetClient)
- return;
- Health = value;
- }
- #region Синхронизация здоровья модуля. Вызывается из модуля
- [NetRPC]
- public void RpcSyncModulHealth(float currentHealth, int modulId)
- {
- OnNetEvent("RpcSyncModulHealth");
- CSMessage.Message("RpcSyncModulHealth " + modulId);
- if (initUnit == InitUnit.NetClient)
- {
- foreach (ModulBase modul in moduls)
- {
- if (modul.modulId == modulId)
- {
- modul.Health = currentHealth;
- }
- }
- }
- }
- #endregion
- #region Синхронизация состояния модуля. Вызывается из модуля
- [NetRPC]
- public void RpcGetModulState(int modulId)
- {
- if (initUnit == InitUnit.Local)
- {
- foreach (ModulBase modul in moduls)
- {
- if (modul.modulId == modulId)
- {
- netId.CallRPC("RpcSyncModulState", (int)modul.ModulStatus, modul.modulId);
- return;
- }
- }
- }
- }
- [NetRPC]
- public void RpcSyncModulState(int state, int modulId)
- {
- if (initUnit == InitUnit.NetClient)
- {
- foreach (ModulBase modul in moduls)
- {
- if (modul.modulId == modulId)
- {
- modul.ModulStatus = (ModulStatus)state;
- return;
- }
- }
- }
- }
- #endregion
- [NetRPC]
- public void RpcGetHealth()
- {
- OnNetEvent("RpcGetHealth");
- if (initUnit != InitUnit.Local)
- return;
- netId.CallRPC("RpcSyncHealth", Health);
- }
- [NetRPC]
- public void RpcShoot(int modulIndex)
- {
- if (initUnit != InitUnit.NetClient)
- return;
- //DArts.DABug.Log("RpcShoot modul " + modulIndex);
- bool shoot = false;
- (moduls[modulIndex] as IShoot).Shoot(out shoot);
- //DArts.DABug.Log("Shoot = " + shoot);
- }
- #region Создаем UI обьекты индикации на удаленных экземплярах. Логика удаленного экземпляра
- [NetRPC]
- public void RpcCreateHudIndicator()
- {
- OnNetEvent("RpcCreateHudIndicator");
- if (initUnit != InitUnit.NetClient)
- return;
- GameObject tmpUi = Instantiate(GameConfig.Singleton.prefabs.onHeadIndicator);
- tmpUi.SendMessage("SetIndicatorTarget", gameObject);
- DArts.DABug.Log("RpcCreateHudIndicator " + _unitName);
- }
- #endregion
- #region Мониторинг обмена данными
- private void OnNetEvent(string nameEvent)
- {
- if (NetEventMonitoring.Singleton != null)
- {
- NetEventMonitoring.Singleton.OnEvent(nameEvent);
- }
- }
- #endregion
- #endregion
- }
Advertisement
Add Comment
Please, Sign In to add comment