playerNetwork.cs 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924
  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using Assets.HeroEditor4D.Common.Scripts.CharacterScripts;
  4. using Assets.HeroEditor4D.Common.Scripts.Enums;
  5. using Mirror;
  6. using TMPro;
  7. using Firebase.Firestore;
  8. using Firebase.Extensions;
  9. using Unity.VisualScripting;
  10. using UnityEngine;
  11. using UnityEngine.SceneManagement;
  12. using GooglePlayGames;
  13. using UnityEngine.SocialPlatforms;
  14. using Firebase.Auth;
  15. using UnityEngine.UI;
  16. using Newtonsoft.Json;
  17. public class playerNetwork : NetworkBehaviour
  18. {
  19. public static playerNetwork localPlayer;
  20. public invitePlayer invitePlayer;
  21. public const float ATTACK_COOLDOWN = 0.6f;
  22. [HideInInspector]
  23. public StatManager statManager;
  24. //public const int XPFORLEVEL = 10;
  25. [SyncVar(hook =nameof(OnHealthChanged))] public int health = 100;
  26. public Character4D character;
  27. public characterManager characterMan;
  28. [SyncVar(hook =nameof(OnDirectionChanged))]
  29. public Vector2 directionNetwork;
  30. [SyncVar(hook =nameof(OnAnimChanged))]
  31. public int animIntNetwork;
  32. [SyncVar(hook = nameof(onKillCountChange))]
  33. public int enemyKillCount;
  34. // public int xp { get{
  35. // int val = 0;
  36. // for(int i =5; i <= enemyKillCount; i+=5){
  37. // val = enemyKillCount;
  38. // }
  39. // return val;
  40. // }}
  41. [SyncVar(hook = nameof(OnXpChanged))]
  42. public int XP;
  43. [SyncVar]
  44. public string myPartyOwner;
  45. public int lvl2 { get{
  46. return GetLevelForKills2(enemyKillCount);
  47. }}
  48. public int GetLevelForKills2(int kills){
  49. int val = 0;
  50. for(int i =10; i <= kills; i+=10){
  51. val ++;
  52. }
  53. return val;
  54. }
  55. public int lvl{
  56. get{
  57. return GetLevelByXp(XP);
  58. }
  59. }
  60. public int GetLevelByXp(int xp){
  61. // int level = Mathf.CeilToInt(Mathf.Sqrt(xp/100f));
  62. // if(level <= 0){level = 1;}
  63. // return level;
  64. int level = Mathf.CeilToInt(Mathf.Log(xp / 100f,2) + 1);
  65. if(level <=0){level = 1;}
  66. return level;
  67. // int level = 1;
  68. // int xpNeeded = 100;
  69. // while (xp >= xpNeeded)
  70. // {
  71. // level++;
  72. // xpNeeded = 100 * (int)Mathf.Pow(2, level - 1);
  73. // }
  74. // return level - 1;
  75. }
  76. public int GetXpForLevel(int level){
  77. if (level <= 0)
  78. level = 1;
  79. return Mathf.FloorToInt(100 * Mathf.Pow(2, level - 1));
  80. }
  81. public float XpSliderVal{
  82. get{
  83. int nextLevelXp = GetXpForLevel(lvl);
  84. int prevLevelXp = GetXpForLevel(lvl-1);
  85. if(nextLevelXp == prevLevelXp){
  86. prevLevelXp = 0;
  87. }
  88. int range = nextLevelXp - prevLevelXp;
  89. // Debug.Log($"{XP-prevLevelXp} / {range}");
  90. //Debug.Log($"next : {nextLevelXp}, prev: {prevLevelXp}, xp:{XP}, xpSince:{XP-prevLevelXp}");
  91. return ((float)(XP-prevLevelXp) / (float)range);
  92. // int nextLevel = lvl+1;
  93. // int curLevelXp = lvl * lvl;
  94. // int nextLevelXp = nextLevel * nextLevel;
  95. // // Debug.Log($"Xp Calc: {XP}-{curLevelXp}/{nextLevelXp} - {curLevelXp}");
  96. // // Debug.Log($"{curLevelXp-XP}/{nextLevelXp - curLevelXp}");
  97. // if(XP == 0){return 0;}
  98. // return 1f - ((float)(curLevelXp - XP) / (float)(nextLevelXp- curLevelXp));
  99. }
  100. }
  101. [SyncVar]
  102. public string playerName;
  103. [SyncVar]
  104. public int playerCoin;
  105. [SyncVar]
  106. public string myCharJson;
  107. public TMP_Text txtEnemyKillCount;
  108. public TMP_Text txtPlayerName;
  109. public TMP_Text questText;
  110. public GameObject questUI;
  111. public TMP_Text coinText;
  112. public TMP_Text xpText;
  113. public TMP_Text lvlText;
  114. public Slider xpSlider;
  115. public GameObject[] xpSliderSlots;
  116. public TMP_Text xpEnableTxt;
  117. //public TMP_Text attackDmgEnableTxt;
  118. public GameObject canvas;
  119. public Slider healthBar;
  120. public Slider armorBar;
  121. public Inventory inventory;
  122. public static Transform localPlayerTransform;
  123. public GameObject healthVfx;
  124. public GameObject damageVfx;
  125. public GameObject levelUpVfx;
  126. public QuestScriptable currentQuest;
  127. public List<QuestAction> questActions;
  128. public List<string> completedQuests;
  129. public GameObject projectile;
  130. public GameObject arrowRange;
  131. public string selectedCharacterJson = CharacterSelection.selectedCharJson;
  132. public void SetActiveQuest(QuestScriptable questData){
  133. currentQuest = questData;
  134. questText.text = questData.questTitle;
  135. questUI.SetActive(true);
  136. foreach(QuestAction quest in questActions){
  137. if(quest.questData == questData){
  138. quest.activate();
  139. }
  140. }
  141. }
  142. public void CompleteQuest(QuestScriptable questData){
  143. if(questData != currentQuest){
  144. Debug.LogError("Completed a quest that wasnt active");
  145. return;
  146. }
  147. completedQuests.Add(currentQuest.questName);
  148. currentQuest = null;
  149. questText.text = "Quest Completed!";
  150. playerCoin += questData.rewardAmount;
  151. coinText.text = playerCoin.ToString();
  152. //add delay
  153. StartCoroutine(DelayUI());
  154. }
  155. public void CancelledQuest(){
  156. questText.text = "Quest Cancelled: " + currentQuest.questTitle;
  157. //
  158. currentQuest = null;
  159. StartCoroutine(DelayUI());
  160. }
  161. IEnumerator DelayUI(){
  162. yield return new WaitForSecondsRealtime(10f);
  163. questUI.SetActive(false);
  164. }
  165. public static void registerQuestAction(QuestAction action){
  166. localPlayerTransform.GetComponent<playerNetwork>().questActions.Add(action);
  167. }
  168. void Awake(){
  169. invitePlayer = GetComponent<invitePlayer>();
  170. rangeEnemyFind = GetComponent<rangeEnemyFinder>();
  171. }
  172. void Start(){
  173. #if UNITY_EDITOR
  174. if(isServer){
  175. playerName = "Player" + Random.Range(0, 100);
  176. }
  177. #endif
  178. if(!isLocalPlayer){
  179. canvas.SetActive(false);
  180. if(!isServer){
  181. CmdRequestCharJson();
  182. }
  183. }else{
  184. localPlayerTransform = transform;
  185. localPlayer = this;
  186. cameraRPG.instance.SetTarget(transform);
  187. #if UNITY_EDITOR
  188. ResetHealthAndArmor();
  189. #else
  190. LoadPlayerData();
  191. #endif
  192. statManager.OnStatsChanged += ConfigArmorHealthSliders;
  193. if(isServer){
  194. playerName = gplayAuth.userNameCloud;
  195. myCharJson = CharacterSelection.selectedCharJson;
  196. RpcBroadcastCharJson(CharacterSelection.selectedCharJson);
  197. }
  198. else{
  199. if(gplayAuth.userNameCloud.Length > 0){
  200. CmdSetName(gplayAuth.userNameCloud);
  201. }else{
  202. CmdSetName("Player" + Random.Range(0, 100));
  203. }
  204. CmdSetCharJson(CharacterSelection.selectedCharJson);
  205. }
  206. }
  207. }
  208. [Command]
  209. public void CmdInvitePlayer(string otherPlayerName){
  210. if(myPartyOwner == null || myPartyOwner.Length == 0){
  211. FindPlayerByName(otherPlayerName).ShowInvite(playerName);
  212. }else{
  213. FindPlayerByName(otherPlayerName).ShowInvite(myPartyOwner);
  214. }
  215. }
  216. public void ShowInvite(string ownerName){
  217. RpcInvitePlayer(ownerName);
  218. }
  219. [ClientRpc]
  220. void RpcInvitePlayer(string playerName){
  221. if(!isLocalPlayer){return;}
  222. invitePlayer.ShowInvite(playerName);
  223. }
  224. [Command]
  225. public void CmdAcceptInvite(string otherPlayerName){
  226. myPartyOwner = otherPlayerName;
  227. }
  228. playerNetwork FindPlayerByName(string playerName){
  229. playerNetwork[] players = FindObjectsOfType<playerNetwork>();
  230. foreach(playerNetwork player in players){
  231. if(player.playerName == playerName){
  232. return player;
  233. }
  234. }
  235. return null;
  236. }
  237. void LoadCharFromJson(string json){
  238. if(json.Length <=0){return;}
  239. character.FromJson(json,true);
  240. }
  241. public void SavePlayerData(){
  242. #if UNITY_EDITOR
  243. return;
  244. #endif
  245. Debug.Log("*** Save Method Got Called ! ***");
  246. if(!isLoaded){
  247. Debug.Log("*** Save Method Return ***");
  248. return;
  249. }
  250. FirebaseFirestore db = FirebaseFirestore.DefaultInstance;
  251. //int playerCoin = int.Parse(coins.text);
  252. Dictionary<string, object> saveValues = new Dictionary<string, object>{
  253. {"playerInventory" , JsonConvert.SerializeObject(inventory.inventoryManager.GetEntries())},
  254. {"playerHealth" , health},
  255. {"playerCoin", playerCoin},
  256. {"killCount", enemyKillCount},
  257. {"xp", XP},
  258. {"completedQuest", completedQuests},
  259. {"playerStats", statManager.PlayerStats},
  260. {"characterJson", selectedCharacterJson},
  261. };
  262. DocumentReference docRef = db.Collection("PlayerData").Document(gplayAuth.userID);
  263. docRef.SetAsync(saveValues).ContinueWithOnMainThread(task => {
  264. if(task.IsCompleted){
  265. Debug.Log("**** Save Completed Firestore ****");
  266. }
  267. else{
  268. Debug.Log("**** Failed to save data to firestore ****");
  269. }
  270. });
  271. }
  272. public bool isLoaded = false;
  273. public void LoadPlayerData(){
  274. #if UNITY_EDITOR
  275. return;
  276. #endif
  277. Debug.Log("**** Data Load method got called ****");
  278. FirebaseFirestore db = FirebaseFirestore.DefaultInstance;
  279. DocumentReference docRef = db.Collection("PlayerData").Document(gplayAuth.userID);
  280. docRef.GetSnapshotAsync().ContinueWithOnMainThread(task => {
  281. DocumentSnapshot snapshot = task.Result;
  282. if(snapshot.Exists){
  283. Debug.Log("**** Found previous Data to load ****");
  284. //load data
  285. // Dictionary<string,object> dic = snapshot.ToDictionary(ServerTimestampBehavior.Estimate);
  286. // Debug.Log("Reading data");
  287. // foreach(KeyValuePair<string,object> item in dic){
  288. // Debug.Log(item.Key + " : " +item.Value.ToString());
  289. // }
  290. //saveNameTxt.text = snapshot.GetValue<string>("playerName");
  291. //load kills
  292. int _enemyKillCount = snapshot.GetValue<int>("killCount");
  293. SetEnemyKillCount(_enemyKillCount);
  294. //load XP
  295. XP = snapshot.GetValue<int>("xp");
  296. //Load coin
  297. int _playerCoin = snapshot.GetValue<int>("playerCoin");
  298. SetPlayerCoins(_playerCoin);
  299. // coinText.text = snapshot.GetValue<int>("playerCoin").ToString();
  300. //Load Health
  301. int savedHealth = snapshot.GetValue<int>("playerHealth");
  302. SetHealth(savedHealth);
  303. ResetHealthAndArmor();
  304. healthBar.value =(savedHealth);
  305. armorBar.value = savedHealth;
  306. //load Inventory
  307. Dictionary<int, string> inventoryGetData = JsonConvert.DeserializeObject<Dictionary<int, string>>(snapshot.GetValue<string>("playerInventory"));
  308. inventory.inventoryManager.SetInventory(inventoryGetData);
  309. completedQuests = snapshot.GetValue<List<string>>("completedQuest");
  310. //stats
  311. statManager.loadFromCloudSave(snapshot.GetValue<Dictionary<string, int>>("playerStats"));
  312. isLoaded = true;
  313. }else{
  314. //show error previous data doesnt exists to load
  315. Debug.Log("**** No previous data to load ****");
  316. isLoaded = true;
  317. }
  318. });
  319. }
  320. [Command]
  321. void CmdSetName(string nameValue){
  322. playerName = nameValue;
  323. }
  324. [Command(requiresAuthority =false)]
  325. void CmdRequestCharJson(){
  326. RpcBroadcastCharJson(myCharJson);
  327. }
  328. [Command]
  329. void CmdSetCharJson(string newValue){
  330. myCharJson = newValue;
  331. RpcBroadcastCharJson(newValue);
  332. LoadCharFromJson(newValue);
  333. }
  334. [ClientRpc]
  335. void RpcBroadcastCharJson(string newValue){
  336. LoadCharFromJson(newValue);
  337. }
  338. void OnDirectionChanged(Vector2 oldVal, Vector2 newVal){
  339. character.SetDirection(newVal);
  340. }
  341. void OnAnimChanged(int oldVal, int newVal){
  342. if(isLocalPlayer){return;}
  343. character.AnimationManager.SetState((CharacterState)newVal);
  344. }
  345. rangeEnemyFinder rangeEnemyFind;
  346. enemyScript closestEnemy => rangeEnemyFind.targetEnemy;
  347. float attackTimer = 0;
  348. [HideInInspector]
  349. public PlayerAttack playerAttack;
  350. void Update(){
  351. if(isLocalPlayer){
  352. if(attackTimer >0){attackTimer-=Time.deltaTime;}
  353. if(isServer){
  354. SetAnimationData(character.Direction, character.Animator.GetInteger("State"));
  355. }else{
  356. CmdUpdateAnim(character.Direction, character.Animator.GetInteger("State"));
  357. }
  358. healthBar.value =(health);
  359. armorBar.value = health;
  360. txtEnemyKillCount.text = enemyKillCount.ToString();
  361. coinText.text = playerCoin.ToString();
  362. txtPlayerName.text = gplayAuth.userNameCloud;
  363. if(myPartyOwner != null && myPartyOwner.Length > 0){
  364. invitePlayer.InParty(myPartyOwner);
  365. }else{
  366. invitePlayer.InParty("");
  367. }
  368. }
  369. ShowXP();
  370. ShowLevel();
  371. }
  372. [Command]
  373. void CmdUpdateAnim(Vector2 direction, int animState){
  374. SetAnimationData(direction, animState);
  375. }
  376. void SetAnimationData(Vector2 direction, int animState){
  377. directionNetwork = direction;
  378. animIntNetwork = animState;
  379. if(!isLocalPlayer){
  380. character.AnimationManager.SetState((CharacterState)animState);
  381. character.SetDirection(direction);
  382. }
  383. }
  384. void OnHealthChanged(int oldVal, int newVal){
  385. if(!isLocalPlayer){return;}
  386. //
  387. if(oldVal < newVal){
  388. GameObject newObject = Instantiate(healthVfx , character.characterTransform());
  389. newObject.transform.localPosition = Vector3.zero;
  390. newObject.transform.parent = transform;
  391. //StartCoroutine (Couroutine_autoDisableVFX(newObject));
  392. vfxScript vfxSc = newObject.AddComponent<vfxScript>();
  393. }else if (oldVal > newVal ){
  394. //damage VFX
  395. GameObject newObject = Instantiate(damageVfx , character.characterTransform());
  396. newObject.transform.localPosition = new Vector3(0, 5f, 0);
  397. newObject.transform.parent = transform;
  398. //StartCoroutine (Couroutine_autoDisableVFX(newObject));
  399. vfxScript vfxSc = newObject.AddComponent<vfxScript>();
  400. // vfxSc.offsetVFX = new Vector3(0, 5f, 0);
  401. // vfxSc.target = character.characterTransform();
  402. }
  403. SavePlayerData();
  404. healthBar.value =(newVal);
  405. armorBar.value = newVal;
  406. }
  407. // IEnumerator Couroutine_autoDisableVFX(GameObject go){
  408. // yield return new WaitForSecondsRealtime(5f);
  409. // Destroy(go);
  410. // }
  411. void onKillCountChange(int oldval, int newval){
  412. if(!isLocalPlayer){return;}
  413. // int prevLevel = GetLevelForKills(oldval);
  414. // int newLevel = GetLevelForKills(newval);
  415. SavePlayerData();
  416. // if(newLevel > prevLevel){
  417. // StartCoroutine(uiTxtDelay(25f));
  418. // }
  419. // if(enemyKillCount == 5 ){
  420. // //SavePlayerData();
  421. // //QuestComplete();
  422. // AddCoin();
  423. // }
  424. }
  425. void OnXpChanged(int oldVal, int newVal){
  426. if(!isLocalPlayer){return;}
  427. int prevLevel = GetLevelByXp(oldVal);
  428. int newLevle = GetLevelByXp(newVal);
  429. if(newLevle > prevLevel){
  430. int levelChange = newLevle - prevLevel;
  431. GameObject newObject = Instantiate(levelUpVfx , character.characterTransform());
  432. newObject.transform.localPosition = Vector3.zero;
  433. newObject.transform.parent = transform;
  434. StartCoroutine(uiTxtDelay(25f, levelChange));
  435. }
  436. }
  437. public void SetHealth(int newvalue){
  438. if(isServer){
  439. health = newvalue;
  440. healthBar.value =(newvalue);
  441. armorBar.value = newvalue;
  442. }else{
  443. CmdSetHealth(newvalue);
  444. }
  445. }
  446. public void SetEnemyKillCount(int newValue){
  447. if(isServer){
  448. enemyKillCount = newValue;
  449. }else{
  450. CmdSetEnemyKillCount(newValue);
  451. }
  452. }
  453. public void SetPlayerCoins(int newVal){
  454. if(isServer){
  455. playerCoin = newVal;
  456. }else{
  457. CmdSetPlayerCoin(newVal);
  458. }
  459. }
  460. [Command]
  461. void CmdSetPlayerCoin(int newVal){
  462. playerCoin = newVal;
  463. }
  464. [Command]
  465. void CmdSetEnemyKillCount(int newValue){
  466. enemyKillCount = newValue;
  467. }
  468. [Command]
  469. void CmdSetHealth(int newValue){
  470. health = newValue;
  471. }
  472. public void TakeDamage(int attackDamage){
  473. serverTakeDmg(attackDamage);
  474. // if(isLocalPlayer){
  475. // takedmg(attackDamage);
  476. // }else if(isServer){
  477. // RpcTakeDamage(attackDamage);
  478. // }
  479. }
  480. void serverTakeDmg(int damage){
  481. health -= damage;
  482. if(health <=0){
  483. RpcDeath();
  484. death();
  485. }
  486. }
  487. float xpTimer = 0;
  488. public void ShowXP(){
  489. if(xpTimer >0){xpTimer -= Time.deltaTime;return;}
  490. xpTimer = 1;
  491. xpText.text = (Mathf.RoundToInt(XP/100f) * 100f).ToString();
  492. xpSlider.value = XpSliderVal;
  493. for(int i=0; i < 10; i++){
  494. float val = (float)i /10f;
  495. xpSliderSlots[i].SetActive(xpSlider.value > val);
  496. }
  497. }
  498. public void ShowLevel(){
  499. lvlText.text = lvl.ToString();
  500. }
  501. public void OnEnemyKilled(int enemyLevel){
  502. //disable take damage and disable healthbar going backwards
  503. int prevValue = lvl;
  504. // SavePlayerData();
  505. enemyKillCount++;
  506. //XP += (int)(enemyScript.XP_GAIN * (enemyLevel/2f));
  507. XP += enemyScript.XP_GAIN_Base + Mathf.FloorToInt(enemyScript.XP_GAIN * (enemyLevel-1));
  508. }
  509. IEnumerator uiTxtDelay (float delayTime, int levelChange){
  510. //enable
  511. xpEnableTxt.gameObject.SetActive(true);
  512. //int attackDamageChange= 5 * levelChange;
  513. //attackDmgEnableTxt.gameObject.SetActive(true);
  514. //attackDmgEnableTxt.text = "Attack Damage + " + attackDamageChange;
  515. yield return new WaitForSecondsRealtime(delayTime);
  516. //disable
  517. xpEnableTxt.gameObject.SetActive(false);
  518. //attackDmgEnableTxt.gameObject.SetActive(false);
  519. }
  520. // public void QuestComplete(){
  521. // //task completion logic
  522. // // Strikethrough the text
  523. // //questText.text = "<s>Kill 5 Enemies to claim 100Golds</s> Completed";
  524. // Debug.Log("First quest completed");
  525. // }
  526. public void AddCoin(){
  527. playerCoin += 100;
  528. coinText.text = playerCoin.ToString();
  529. }
  530. [ClientRpc]
  531. public void RpcDeath(){
  532. death();
  533. }
  534. public bool isDead = false;
  535. public void death(){
  536. Debug.Log("Death called");
  537. character.AnimationManager.Die();
  538. isDead = true;
  539. StartCoroutine(CouroutineWaitDeath());
  540. // throw new System.Exception();
  541. }
  542. IEnumerator CouroutineWaitDeath (){
  543. yield return new WaitForSecondsRealtime(3);
  544. isDead = false;
  545. playerRespawn();
  546. }
  547. public void OnAttack(){
  548. if(attackTimer > 0){
  549. return;
  550. }
  551. //characterMan.SetActiveWeapon(78);
  552. attackTimer = ATTACK_COOLDOWN;
  553. if(isLocalPlayer){
  554. PlayAttackAnim();
  555. playerAttack.Attack(false);
  556. if(isServer){
  557. RpcPlayAttackAnim();
  558. }else{
  559. CmdPlayAttackAnim();
  560. }
  561. }
  562. }
  563. [SerializeField] public float arrowSpeed = 2.0f;
  564. [SerializeField] public float arrowShootOffset = 1;
  565. [SerializeField] public float arrowShootHeightOffset = 1;
  566. public void OnRangeAttack(){
  567. if(attackTimer>0){
  568. return;
  569. }
  570. if(closestEnemy==null){return;}
  571. attackTimer = ATTACK_COOLDOWN;
  572. characterMan.EquipBow();
  573. PlayAttackAnim();
  574. StartCoroutine(ArrowShootDelay());
  575. // arrowRange.transform.position = startingPosition;
  576. //TODO: Deal Damage once it hits enemy
  577. }
  578. public float arrowDelay;
  579. IEnumerator ArrowShootDelay (){
  580. yield return new WaitForSeconds(arrowDelay);
  581. Vector3 startingPosition = transform.position ;
  582. Vector3 destination = closestEnemy.transform.position;
  583. //TODO: Move attack projectile from startingPosition to destination
  584. Vector3 direction = (destination - startingPosition).normalized;
  585. startingPosition += (direction * arrowShootOffset);
  586. startingPosition += (Vector3.up * arrowShootHeightOffset);
  587. destination += (Vector3.up * arrowShootHeightOffset);
  588. // Quaternion rotation = Quaternion.LookRotation(direction);
  589. float angle = Mathf.Atan2(direction.y, direction.x) * Mathf.Rad2Deg;
  590. Quaternion rotation = Quaternion.Euler(0,0,angle - 90f);
  591. GameObject newArrow = Instantiate(arrowRange , transform.position + (direction * arrowShootOffset) , rotation);
  592. StartCoroutine(moveArrow(newArrow.transform , startingPosition , destination , closestEnemy));
  593. }
  594. public int RangeDmg = 10;
  595. IEnumerator moveArrow (Transform arrow , Vector3 start, Vector3 destination, enemyScript target ){
  596. float dist = Vector3.Distance(start , destination);
  597. float duration = dist/arrowSpeed;
  598. float timer = 0f;
  599. while(timer < duration){
  600. arrow.position = Vector3.Lerp(start , destination , timer/duration);
  601. timer += Time.deltaTime;
  602. yield return null;
  603. }
  604. target.TakeDamage(RangeDmg, netId);
  605. Destroy(arrow.gameObject);
  606. }
  607. public int MagicAttackWeaponIndex = 52;
  608. public void OnMagicAttack(){
  609. if(attackTimer > 0){
  610. return;
  611. }
  612. attackTimer = ATTACK_COOLDOWN;
  613. //characterMan.SetActiveWeapon(MagicAttackWeaponIndex);
  614. if(isLocalPlayer){
  615. PlayAttackAnim();
  616. //?
  617. playerAttack.MagicalAttack();
  618. playerAttack.Attack(true);
  619. if(isServer){
  620. RpcPlayAttackAnim();
  621. }else{
  622. CmdPlayAttackAnim();
  623. }
  624. }
  625. }
  626. [Command]
  627. void CmdPlayAttackAnim(){
  628. PlayAttackAnim();
  629. RpcPlayAttackAnim();
  630. }
  631. [ClientRpc]
  632. void RpcPlayAttackAnim(){
  633. if(isLocalPlayer){return;}
  634. PlayAttackAnim();
  635. }
  636. void PlayAttackAnim(){
  637. switch (character.WeaponType)
  638. {
  639. case WeaponType.Melee1H:
  640. case WeaponType.Paired:
  641. character.AnimationManager.Slash(twoHanded: false);
  642. break;
  643. case WeaponType.Melee2H:
  644. character.AnimationManager.Slash(twoHanded: true);
  645. break;
  646. case WeaponType.Bow:
  647. character.AnimationManager.ShotBow();
  648. break;
  649. }
  650. }
  651. public void playerRespawn(){
  652. Debug.Log("Respawning");
  653. // healthBar.SetMaxHealth(statManager.GetEffectiveValue("health"));
  654. ResetHealthAndArmor();
  655. healthBar.value = health;
  656. character.AnimationManager.SetState(CharacterState.Idle);
  657. Transform newSpawnLocationPlayer = GameManager.instance.spawnPointsPlayer.GetChild(Random.Range(0,GameManager.instance.spawnPointsPlayer.childCount));
  658. transform.position = newSpawnLocationPlayer.position;
  659. }
  660. void ResetHealthAndArmor(){
  661. healthBar.maxValue = statManager.GetEffectiveValue("health");
  662. health = statManager.GetEffectiveValue("health") + statManager.GetEffectiveValue("defence");
  663. // Debug.Log($"Setting armor bar, maxVal:{health}, minVal:{healthBar.maxValue}, val:{health}");
  664. armorBar.maxValue = health;
  665. armorBar.minValue = healthBar.maxValue;
  666. armorBar.value = health;
  667. }
  668. void ConfigArmorHealthSliders(){
  669. healthBar.maxValue = statManager.GetEffectiveValue("health");
  670. float maxHealth = statManager.GetEffectiveValue("health") + statManager.GetEffectiveValue("defence");
  671. // Debug.Log($"Setting armor bar, maxVal:{health}, minVal:{healthBar.maxValue}, val:{health}");
  672. armorBar.maxValue = maxHealth;
  673. armorBar.minValue = healthBar.maxValue;
  674. armorBar.value = health;
  675. healthBar.value = health;
  676. }
  677. //Pickup
  678. public void PickupObject(pickup item){
  679. if(!isServer){ Debug.LogError("Cant call command on client, 403"); return; }
  680. if(isLocalPlayer){
  681. pickupObject(item.lootData.type);
  682. }else{
  683. RpcPickupObject(item.lootData.type);
  684. }
  685. }
  686. [ClientRpc]
  687. void RpcPickupObject(string type){
  688. if(isLocalPlayer){
  689. pickupObject(type);
  690. }
  691. }
  692. void pickupObject(string type){
  693. inventory.AddItem(type);
  694. }
  695. public void DropPickup(string type){
  696. if(isServer){
  697. GameManager.instance.SpawnPickup(type,transform.position + new Vector3(0.85f,0.6f));
  698. }else{
  699. CmdDropPickup(type);
  700. }
  701. }
  702. [Command]
  703. void CmdDropPickup(string type){
  704. GameManager.instance.SpawnPickup(type,transform.position + new Vector3(4,0));
  705. }
  706. int magicalDmg = 0;
  707. public void MagicalAttack(Vector3 direction, float magicalProjectileSpawnOffset, int dmg)
  708. {
  709. if (isServer)
  710. {
  711. magicalAttack(direction, magicalProjectileSpawnOffset, dmg);
  712. }
  713. else
  714. {
  715. CmdMagicalAttack(direction, magicalProjectileSpawnOffset, dmg);
  716. }
  717. }
  718. [Command]
  719. void CmdMagicalAttack(Vector3 direction, float magicalProjectileSpawnOffset, int dmg)
  720. {
  721. magicalAttack(direction, magicalProjectileSpawnOffset, dmg);
  722. }
  723. void magicalAttack(Vector3 direction, float magicalProjectileSpawnOffset, int dmg)
  724. {
  725. magicalDmg = dmg;
  726. GameObject projectileSpawned = Instantiate(projectile, transform.position + (direction * magicalProjectileSpawnOffset), Quaternion.identity);
  727. RangeProjectile _projectile = projectileSpawned.GetComponent<RangeProjectile>();
  728. _projectile.direction = direction;
  729. _projectile.OnHit.AddListener(OnMagicalHit);
  730. _projectile.shooterId = netId;
  731. NetworkServer.Spawn(projectileSpawned);
  732. }
  733. void OnMagicalHit(enemyScript victim)
  734. {
  735. //magical damage with intelligance stat ?
  736. //int damageamount = magicalDmg + (lvl * 5);
  737. int damageamount = magicalDmg + (statManager.GetEffectiveValue("intelligence")*2);
  738. Debug.Log("magic damage amount " + damageamount);
  739. victim.TakeMagicalDamage(damageamount, netId);
  740. }
  741. public void GoBackMenu(){
  742. startClient.instance.networkManager.StopClient();
  743. SceneManager.LoadScene("GameLogin");
  744. #if UNITY_EDITOR || UNITY_SERVER || UNITY_STANDALONE_WIN
  745. #else
  746. PlayGamesPlatform.Instance.SignOut();
  747. Firebase.Auth.FirebaseAuth.DefaultInstance.SignOut();
  748. #endif
  749. }
  750. }