playerNetwork.cs 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921
  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. // for(int i =0; i < 2000; i+=10){
  174. // int level = GetLevelByXp(i);
  175. // int xp = GetXpForLevel(level);
  176. // Debug.Log($"{i} : {level} : {xp}");
  177. // }
  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. CmdSetName(gplayAuth.userNameCloud);
  200. CmdSetCharJson(CharacterSelection.selectedCharJson);
  201. }
  202. }
  203. }
  204. [Command]
  205. public void CmdInvitePlayer(string otherPlayerName){
  206. if(myPartyOwner == null || myPartyOwner.Length == 0){
  207. FindPlayerByName(otherPlayerName).ShowInvite(playerName);
  208. }else{
  209. FindPlayerByName(otherPlayerName).ShowInvite(myPartyOwner);
  210. }
  211. }
  212. public void ShowInvite(string ownerName){
  213. RpcInvitePlayer(ownerName);
  214. }
  215. [ClientRpc]
  216. void RpcInvitePlayer(string playerName){
  217. if(!isLocalPlayer){return;}
  218. invitePlayer.ShowInvite(playerName);
  219. }
  220. [Command]
  221. public void CmdAcceptInvite(string otherPlayerName){
  222. myPartyOwner = otherPlayerName;
  223. }
  224. playerNetwork FindPlayerByName(string playerName){
  225. playerNetwork[] players = FindObjectsOfType<playerNetwork>();
  226. foreach(playerNetwork player in players){
  227. if(player.playerName == playerName){
  228. return player;
  229. }
  230. }
  231. return null;
  232. }
  233. void LoadCharFromJson(string json){
  234. if(json.Length <=0){return;}
  235. character.FromJson(json,true);
  236. }
  237. public void SavePlayerData(){
  238. #if UNITY_EDITOR
  239. return;
  240. #endif
  241. Debug.Log("*** Save Method Got Called ! ***");
  242. if(!isLoaded){
  243. Debug.Log("*** Save Method Return ***");
  244. return;
  245. }
  246. FirebaseFirestore db = FirebaseFirestore.DefaultInstance;
  247. //int playerCoin = int.Parse(coins.text);
  248. Dictionary<string, object> saveValues = new Dictionary<string, object>{
  249. {"playerInventory" , JsonConvert.SerializeObject(inventory.inventoryManager.GetEntries())},
  250. {"playerHealth" , health},
  251. {"playerCoin", playerCoin},
  252. {"killCount", enemyKillCount},
  253. {"xp", XP},
  254. {"completedQuest", completedQuests},
  255. {"playerStats", statManager.PlayerStats},
  256. {"characterJson", selectedCharacterJson},
  257. };
  258. DocumentReference docRef = db.Collection("PlayerData").Document(gplayAuth.userID);
  259. docRef.SetAsync(saveValues).ContinueWithOnMainThread(task => {
  260. if(task.IsCompleted){
  261. Debug.Log("**** Save Completed Firestore ****");
  262. }
  263. else{
  264. Debug.Log("**** Failed to save data to firestore ****");
  265. }
  266. });
  267. }
  268. public bool isLoaded = false;
  269. public void LoadPlayerData(){
  270. #if UNITY_EDITOR
  271. return;
  272. #endif
  273. Debug.Log("**** Data Load method got called ****");
  274. FirebaseFirestore db = FirebaseFirestore.DefaultInstance;
  275. DocumentReference docRef = db.Collection("PlayerData").Document(gplayAuth.userID);
  276. docRef.GetSnapshotAsync().ContinueWithOnMainThread(task => {
  277. DocumentSnapshot snapshot = task.Result;
  278. if(snapshot.Exists){
  279. Debug.Log("**** Found previous Data to load ****");
  280. //load data
  281. // Dictionary<string,object> dic = snapshot.ToDictionary(ServerTimestampBehavior.Estimate);
  282. // Debug.Log("Reading data");
  283. // foreach(KeyValuePair<string,object> item in dic){
  284. // Debug.Log(item.Key + " : " +item.Value.ToString());
  285. // }
  286. //saveNameTxt.text = snapshot.GetValue<string>("playerName");
  287. //load kills
  288. int _enemyKillCount = snapshot.GetValue<int>("killCount");
  289. SetEnemyKillCount(_enemyKillCount);
  290. //load XP
  291. XP = snapshot.GetValue<int>("xp");
  292. //Load coin
  293. int _playerCoin = snapshot.GetValue<int>("playerCoin");
  294. SetPlayerCoins(_playerCoin);
  295. // coinText.text = snapshot.GetValue<int>("playerCoin").ToString();
  296. //Load Health
  297. int savedHealth = snapshot.GetValue<int>("playerHealth");
  298. SetHealth(savedHealth);
  299. ResetHealthAndArmor();
  300. healthBar.value =(savedHealth);
  301. armorBar.value = savedHealth;
  302. //load Inventory
  303. Dictionary<int, string> inventoryGetData = JsonConvert.DeserializeObject<Dictionary<int, string>>(snapshot.GetValue<string>("playerInventory"));
  304. inventory.inventoryManager.SetInventory(inventoryGetData);
  305. completedQuests = snapshot.GetValue<List<string>>("completedQuest");
  306. //stats
  307. statManager.loadFromCloudSave(snapshot.GetValue<Dictionary<string, int>>("playerStats"));
  308. isLoaded = true;
  309. }else{
  310. //show error previous data doesnt exists to load
  311. Debug.Log("**** No previous data to load ****");
  312. isLoaded = true;
  313. }
  314. });
  315. }
  316. [Command]
  317. void CmdSetName(string nameValue){
  318. playerName = nameValue;
  319. }
  320. [Command(requiresAuthority =false)]
  321. void CmdRequestCharJson(){
  322. RpcBroadcastCharJson(myCharJson);
  323. }
  324. [Command]
  325. void CmdSetCharJson(string newValue){
  326. myCharJson = newValue;
  327. RpcBroadcastCharJson(newValue);
  328. LoadCharFromJson(newValue);
  329. }
  330. [ClientRpc]
  331. void RpcBroadcastCharJson(string newValue){
  332. LoadCharFromJson(newValue);
  333. }
  334. void OnDirectionChanged(Vector2 oldVal, Vector2 newVal){
  335. character.SetDirection(newVal);
  336. }
  337. void OnAnimChanged(int oldVal, int newVal){
  338. if(isLocalPlayer){return;}
  339. character.AnimationManager.SetState((CharacterState)newVal);
  340. }
  341. rangeEnemyFinder rangeEnemyFind;
  342. enemyScript closestEnemy => rangeEnemyFind.targetEnemy;
  343. float attackTimer = 0;
  344. [HideInInspector]
  345. public PlayerAttack playerAttack;
  346. void Update(){
  347. if(isLocalPlayer){
  348. if(attackTimer >0){attackTimer-=Time.deltaTime;}
  349. if(isServer){
  350. SetAnimationData(character.Direction, character.Animator.GetInteger("State"));
  351. }else{
  352. CmdUpdateAnim(character.Direction, character.Animator.GetInteger("State"));
  353. }
  354. healthBar.value =(health);
  355. armorBar.value = health;
  356. txtEnemyKillCount.text = enemyKillCount.ToString();
  357. coinText.text = playerCoin.ToString();
  358. txtPlayerName.text = gplayAuth.userNameCloud;
  359. if(myPartyOwner != null && myPartyOwner.Length > 0){
  360. invitePlayer.InParty(myPartyOwner);
  361. }else{
  362. invitePlayer.InParty("");
  363. }
  364. }
  365. ShowXP();
  366. ShowLevel();
  367. }
  368. [Command]
  369. void CmdUpdateAnim(Vector2 direction, int animState){
  370. SetAnimationData(direction, animState);
  371. }
  372. void SetAnimationData(Vector2 direction, int animState){
  373. directionNetwork = direction;
  374. animIntNetwork = animState;
  375. if(!isLocalPlayer){
  376. character.AnimationManager.SetState((CharacterState)animState);
  377. character.SetDirection(direction);
  378. }
  379. }
  380. void OnHealthChanged(int oldVal, int newVal){
  381. if(!isLocalPlayer){return;}
  382. //
  383. if(oldVal < newVal){
  384. GameObject newObject = Instantiate(healthVfx , character.characterTransform());
  385. newObject.transform.localPosition = Vector3.zero;
  386. newObject.transform.parent = transform;
  387. //StartCoroutine (Couroutine_autoDisableVFX(newObject));
  388. vfxScript vfxSc = newObject.AddComponent<vfxScript>();
  389. }else if (oldVal > newVal ){
  390. //damage VFX
  391. GameObject newObject = Instantiate(damageVfx , character.characterTransform());
  392. newObject.transform.localPosition = new Vector3(0, 5f, 0);
  393. newObject.transform.parent = transform;
  394. //StartCoroutine (Couroutine_autoDisableVFX(newObject));
  395. vfxScript vfxSc = newObject.AddComponent<vfxScript>();
  396. // vfxSc.offsetVFX = new Vector3(0, 5f, 0);
  397. // vfxSc.target = character.characterTransform();
  398. }
  399. SavePlayerData();
  400. healthBar.value =(newVal);
  401. armorBar.value = newVal;
  402. }
  403. // IEnumerator Couroutine_autoDisableVFX(GameObject go){
  404. // yield return new WaitForSecondsRealtime(5f);
  405. // Destroy(go);
  406. // }
  407. void onKillCountChange(int oldval, int newval){
  408. if(!isLocalPlayer){return;}
  409. // int prevLevel = GetLevelForKills(oldval);
  410. // int newLevel = GetLevelForKills(newval);
  411. SavePlayerData();
  412. // if(newLevel > prevLevel){
  413. // StartCoroutine(uiTxtDelay(25f));
  414. // }
  415. // if(enemyKillCount == 5 ){
  416. // //SavePlayerData();
  417. // //QuestComplete();
  418. // AddCoin();
  419. // }
  420. }
  421. void OnXpChanged(int oldVal, int newVal){
  422. if(!isLocalPlayer){return;}
  423. int prevLevel = GetLevelByXp(oldVal);
  424. int newLevle = GetLevelByXp(newVal);
  425. if(newLevle > prevLevel){
  426. int levelChange = newLevle - prevLevel;
  427. GameObject newObject = Instantiate(levelUpVfx , character.characterTransform());
  428. newObject.transform.localPosition = Vector3.zero;
  429. newObject.transform.parent = transform;
  430. StartCoroutine(uiTxtDelay(25f, levelChange));
  431. }
  432. }
  433. public void SetHealth(int newvalue){
  434. if(isServer){
  435. health = newvalue;
  436. healthBar.value =(newvalue);
  437. armorBar.value = newvalue;
  438. }else{
  439. CmdSetHealth(newvalue);
  440. }
  441. }
  442. public void SetEnemyKillCount(int newValue){
  443. if(isServer){
  444. enemyKillCount = newValue;
  445. }else{
  446. CmdSetEnemyKillCount(newValue);
  447. }
  448. }
  449. public void SetPlayerCoins(int newVal){
  450. if(isServer){
  451. playerCoin = newVal;
  452. }else{
  453. CmdSetPlayerCoin(newVal);
  454. }
  455. }
  456. [Command]
  457. void CmdSetPlayerCoin(int newVal){
  458. playerCoin = newVal;
  459. }
  460. [Command]
  461. void CmdSetEnemyKillCount(int newValue){
  462. enemyKillCount = newValue;
  463. }
  464. [Command]
  465. void CmdSetHealth(int newValue){
  466. health = newValue;
  467. }
  468. public void TakeDamage(int attackDamage){
  469. serverTakeDmg(attackDamage);
  470. // if(isLocalPlayer){
  471. // takedmg(attackDamage);
  472. // }else if(isServer){
  473. // RpcTakeDamage(attackDamage);
  474. // }
  475. }
  476. void serverTakeDmg(int damage){
  477. health -= damage;
  478. if(health <=0){
  479. RpcDeath();
  480. death();
  481. }
  482. }
  483. float xpTimer = 0;
  484. public void ShowXP(){
  485. if(xpTimer >0){xpTimer -= Time.deltaTime;return;}
  486. xpTimer = 1;
  487. xpText.text = (Mathf.RoundToInt(XP/100f) * 100f).ToString();
  488. xpSlider.value = XpSliderVal;
  489. for(int i=0; i < 10; i++){
  490. float val = (float)i /10f;
  491. xpSliderSlots[i].SetActive(xpSlider.value > val);
  492. }
  493. }
  494. public void ShowLevel(){
  495. lvlText.text = lvl.ToString();
  496. }
  497. public void OnEnemyKilled(int enemyLevel){
  498. //disable take damage and disable healthbar going backwards
  499. int prevValue = lvl;
  500. // SavePlayerData();
  501. enemyKillCount++;
  502. //XP += (int)(enemyScript.XP_GAIN * (enemyLevel/2f));
  503. XP += enemyScript.XP_GAIN_Base + Mathf.FloorToInt(enemyScript.XP_GAIN * (enemyLevel-1));
  504. }
  505. IEnumerator uiTxtDelay (float delayTime, int levelChange){
  506. //enable
  507. xpEnableTxt.gameObject.SetActive(true);
  508. //int attackDamageChange= 5 * levelChange;
  509. //attackDmgEnableTxt.gameObject.SetActive(true);
  510. //attackDmgEnableTxt.text = "Attack Damage + " + attackDamageChange;
  511. yield return new WaitForSecondsRealtime(delayTime);
  512. //disable
  513. xpEnableTxt.gameObject.SetActive(false);
  514. //attackDmgEnableTxt.gameObject.SetActive(false);
  515. }
  516. // public void QuestComplete(){
  517. // //task completion logic
  518. // // Strikethrough the text
  519. // //questText.text = "<s>Kill 5 Enemies to claim 100Golds</s> Completed";
  520. // Debug.Log("First quest completed");
  521. // }
  522. public void AddCoin(){
  523. playerCoin += 100;
  524. coinText.text = playerCoin.ToString();
  525. }
  526. [ClientRpc]
  527. public void RpcDeath(){
  528. death();
  529. }
  530. public bool isDead = false;
  531. public void death(){
  532. Debug.Log("Death called");
  533. character.AnimationManager.Die();
  534. isDead = true;
  535. StartCoroutine(CouroutineWaitDeath());
  536. // throw new System.Exception();
  537. }
  538. IEnumerator CouroutineWaitDeath (){
  539. yield return new WaitForSecondsRealtime(3);
  540. isDead = false;
  541. playerRespawn();
  542. }
  543. public void OnAttack(){
  544. if(attackTimer > 0){
  545. return;
  546. }
  547. //characterMan.SetActiveWeapon(78);
  548. attackTimer = ATTACK_COOLDOWN;
  549. if(isLocalPlayer){
  550. PlayAttackAnim();
  551. playerAttack.Attack(false);
  552. if(isServer){
  553. RpcPlayAttackAnim();
  554. }else{
  555. CmdPlayAttackAnim();
  556. }
  557. }
  558. }
  559. [SerializeField] public float arrowSpeed = 2.0f;
  560. [SerializeField] public float arrowShootOffset = 1;
  561. [SerializeField] public float arrowShootHeightOffset = 1;
  562. public void OnRangeAttack(){
  563. if(attackTimer>0){
  564. return;
  565. }
  566. if(closestEnemy==null){return;}
  567. attackTimer = ATTACK_COOLDOWN;
  568. characterMan.EquipBow();
  569. PlayAttackAnim();
  570. StartCoroutine(ArrowShootDelay());
  571. // arrowRange.transform.position = startingPosition;
  572. //TODO: Deal Damage once it hits enemy
  573. }
  574. public float arrowDelay;
  575. IEnumerator ArrowShootDelay (){
  576. yield return new WaitForSeconds(arrowDelay);
  577. Vector3 startingPosition = transform.position ;
  578. Vector3 destination = closestEnemy.transform.position;
  579. //TODO: Move attack projectile from startingPosition to destination
  580. Vector3 direction = (destination - startingPosition).normalized;
  581. startingPosition += (direction * arrowShootOffset);
  582. startingPosition += (Vector3.up * arrowShootHeightOffset);
  583. destination += (Vector3.up * arrowShootHeightOffset);
  584. // Quaternion rotation = Quaternion.LookRotation(direction);
  585. float angle = Mathf.Atan2(direction.y, direction.x) * Mathf.Rad2Deg;
  586. Quaternion rotation = Quaternion.Euler(0,0,angle - 90f);
  587. GameObject newArrow = Instantiate(arrowRange , transform.position + (direction * arrowShootOffset) , rotation);
  588. StartCoroutine(moveArrow(newArrow.transform , startingPosition , destination , closestEnemy));
  589. }
  590. public int RangeDmg = 10;
  591. IEnumerator moveArrow (Transform arrow , Vector3 start, Vector3 destination, enemyScript target ){
  592. float dist = Vector3.Distance(start , destination);
  593. float duration = dist/arrowSpeed;
  594. float timer = 0f;
  595. while(timer < duration){
  596. arrow.position = Vector3.Lerp(start , destination , timer/duration);
  597. timer += Time.deltaTime;
  598. yield return null;
  599. }
  600. target.TakeDamage(RangeDmg, netId);
  601. Destroy(arrow.gameObject);
  602. }
  603. public int MagicAttackWeaponIndex = 52;
  604. public void OnMagicAttack(){
  605. if(attackTimer > 0){
  606. return;
  607. }
  608. attackTimer = ATTACK_COOLDOWN;
  609. //characterMan.SetActiveWeapon(MagicAttackWeaponIndex);
  610. if(isLocalPlayer){
  611. PlayAttackAnim();
  612. //?
  613. playerAttack.MagicalAttack();
  614. playerAttack.Attack(true);
  615. if(isServer){
  616. RpcPlayAttackAnim();
  617. }else{
  618. CmdPlayAttackAnim();
  619. }
  620. }
  621. }
  622. [Command]
  623. void CmdPlayAttackAnim(){
  624. PlayAttackAnim();
  625. RpcPlayAttackAnim();
  626. }
  627. [ClientRpc]
  628. void RpcPlayAttackAnim(){
  629. if(isLocalPlayer){return;}
  630. PlayAttackAnim();
  631. }
  632. void PlayAttackAnim(){
  633. switch (character.WeaponType)
  634. {
  635. case WeaponType.Melee1H:
  636. case WeaponType.Paired:
  637. character.AnimationManager.Slash(twoHanded: false);
  638. break;
  639. case WeaponType.Melee2H:
  640. character.AnimationManager.Slash(twoHanded: true);
  641. break;
  642. case WeaponType.Bow:
  643. character.AnimationManager.ShotBow();
  644. break;
  645. }
  646. }
  647. public void playerRespawn(){
  648. Debug.Log("Respawning");
  649. // healthBar.SetMaxHealth(statManager.GetEffectiveValue("health"));
  650. ResetHealthAndArmor();
  651. healthBar.value = health;
  652. character.AnimationManager.SetState(CharacterState.Idle);
  653. Transform newSpawnLocationPlayer = GameManager.instance.spawnPointsPlayer.GetChild(Random.Range(0,GameManager.instance.spawnPointsPlayer.childCount));
  654. transform.position = newSpawnLocationPlayer.position;
  655. }
  656. void ResetHealthAndArmor(){
  657. healthBar.maxValue = statManager.GetEffectiveValue("health");
  658. health = statManager.GetEffectiveValue("health") + statManager.GetEffectiveValue("defence");
  659. // Debug.Log($"Setting armor bar, maxVal:{health}, minVal:{healthBar.maxValue}, val:{health}");
  660. armorBar.maxValue = health;
  661. armorBar.minValue = healthBar.maxValue;
  662. armorBar.value = health;
  663. }
  664. void ConfigArmorHealthSliders(){
  665. healthBar.maxValue = statManager.GetEffectiveValue("health");
  666. float maxHealth = statManager.GetEffectiveValue("health") + statManager.GetEffectiveValue("defence");
  667. // Debug.Log($"Setting armor bar, maxVal:{health}, minVal:{healthBar.maxValue}, val:{health}");
  668. armorBar.maxValue = maxHealth;
  669. armorBar.minValue = healthBar.maxValue;
  670. armorBar.value = health;
  671. healthBar.value = health;
  672. }
  673. //Pickup
  674. public void PickupObject(pickup item){
  675. if(!isServer){ Debug.LogError("Cant call command on client, 403"); return; }
  676. if(isLocalPlayer){
  677. pickupObject(item.lootData.type);
  678. }else{
  679. RpcPickupObject(item.lootData.type);
  680. }
  681. }
  682. [ClientRpc]
  683. void RpcPickupObject(string type){
  684. if(isLocalPlayer){
  685. pickupObject(type);
  686. }
  687. }
  688. void pickupObject(string type){
  689. inventory.AddItem(type);
  690. }
  691. public void DropPickup(string type){
  692. if(isServer){
  693. GameManager.instance.SpawnPickup(type,transform.position + new Vector3(0.85f,0.6f));
  694. }else{
  695. CmdDropPickup(type);
  696. }
  697. }
  698. [Command]
  699. void CmdDropPickup(string type){
  700. GameManager.instance.SpawnPickup(type,transform.position + new Vector3(4,0));
  701. }
  702. int magicalDmg = 0;
  703. public void MagicalAttack(Vector3 direction, float magicalProjectileSpawnOffset, int dmg)
  704. {
  705. if (isServer)
  706. {
  707. magicalAttack(direction, magicalProjectileSpawnOffset, dmg);
  708. }
  709. else
  710. {
  711. CmdMagicalAttack(direction, magicalProjectileSpawnOffset, dmg);
  712. }
  713. }
  714. [Command]
  715. void CmdMagicalAttack(Vector3 direction, float magicalProjectileSpawnOffset, int dmg)
  716. {
  717. magicalAttack(direction, magicalProjectileSpawnOffset, dmg);
  718. }
  719. void magicalAttack(Vector3 direction, float magicalProjectileSpawnOffset, int dmg)
  720. {
  721. magicalDmg = dmg;
  722. GameObject projectileSpawned = Instantiate(projectile, transform.position + (direction * magicalProjectileSpawnOffset), Quaternion.identity);
  723. RangeProjectile _projectile = projectileSpawned.GetComponent<RangeProjectile>();
  724. _projectile.direction = direction;
  725. _projectile.OnHit.AddListener(OnMagicalHit);
  726. _projectile.shooterId = netId;
  727. NetworkServer.Spawn(projectileSpawned);
  728. }
  729. void OnMagicalHit(enemyScript victim)
  730. {
  731. //magical damage with intelligance stat ?
  732. //int damageamount = magicalDmg + (lvl * 5);
  733. int damageamount = magicalDmg + (statManager.GetEffectiveValue("intelligence")*2);
  734. Debug.Log("magic damage amount " + damageamount);
  735. victim.TakeMagicalDamage(damageamount, netId);
  736. }
  737. public void GoBackMenu(){
  738. startClient.instance.networkManager.StopClient();
  739. SceneManager.LoadScene("GameLogin");
  740. #if UNITY_EDITOR || UNITY_SERVER || UNITY_STANDALONE_WIN
  741. #else
  742. PlayGamesPlatform.Instance.SignOut();
  743. Firebase.Auth.FirebaseAuth.DefaultInstance.SignOut();
  744. #endif
  745. }
  746. }