playerNetwork.cs 29 KB

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