playerNetwork.cs 27 KB

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