playerNetwork.cs 27 KB

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