mmorpg/Assets/Script/playerNetwork.cs
2024-03-18 23:09:45 +05:30

500 lines
14 KiB
C#

using System.Collections;
using System.Collections.Generic;
using Assets.HeroEditor4D.Common.Scripts.CharacterScripts;
using Assets.HeroEditor4D.Common.Scripts.Enums;
using Mirror;
using TMPro;
using Firebase.Firestore;
using Firebase.Extensions;
using Unity.VisualScripting;
using UnityEngine;
using UnityEngine.SceneManagement;
using GooglePlayGames;
using UnityEngine.SocialPlatforms;
using Firebase.Auth;
public class playerNetwork : NetworkBehaviour
{
[SyncVar(hook =nameof(OnHealthChanged))] public int health = 100;
public Character4D character;
[SyncVar(hook =nameof(OnDirectionChanged))]
public Vector2 directionNetwork;
[SyncVar(hook =nameof(OnAnimChanged))]
public int animIntNetwork;
[SyncVar(hook = nameof(onKillCountChange))]
public int enemyKillCount;
public int xp { get{
int val = 0;
for(int i =5; i <= enemyKillCount; i+=5){
val = enemyKillCount;
}
return val;
}}
public int lvl { get{
return GetLevelForKills(enemyKillCount);
}}
public int GetLevelForKills(int kills){
int val = 0;
for(int i =5; i <= kills; i+=5){
val ++;
}
return val;
}
[SyncVar]
public string playerName;
[SyncVar]
public int playerCoin;
public TMP_Text txtEnemyKillCount;
public TMP_Text txtPlayerName;
public TMP_Text questText;
public GameObject questUI;
public TMP_Text coinText;
public TMP_Text xpText;
public TMP_Text lvlText;
public TMP_Text xpEnableTxt;
public TMP_Text attackDmgEnableTxt;
public GameObject canvas;
public healthBar healthBar;
public Inventory inventory;
public static Transform localPlayerTransform;
public GameObject healthVfx;
public GameObject damageVfx;
public QuestScriptable currentQuest;
public List<QuestAction> questActions;
public List<string> completedQuests;
public void QuestFunction(QuestScriptable questData){
currentQuest = questData;
questText.text = questData.questTitle;
questUI.SetActive(true);
foreach(QuestAction quest in questActions){
if(quest.questData == questData){
quest.activate();
}
}
}
public void CompleteQuest(QuestScriptable questData){
if(questData != currentQuest){
Debug.LogError("Completed a quest that wasnt even active");
return;
}
completedQuests.Add(currentQuest.name);
currentQuest = null;
questText.text = "Quest Completed! Found 1000 coins from Cave-Chest";
playerCoin += questData.rewardAmount;
coinText.text = playerCoin.ToString();
//add delay
StartCoroutine(DelayUI());
}
IEnumerator DelayUI(){
yield return new WaitForSecondsRealtime(10f);
questUI.SetActive(false);
}
public static void registerQuestAction(QuestAction action){
localPlayerTransform.GetComponent<playerNetwork>().questActions.Add(action);
}
void Start(){
if(!isLocalPlayer){
canvas.SetActive(false);
}else{
localPlayerTransform = transform;
cameraRPG.instance.SetTarget(transform);
if(isServer){
playerName = gplayAuth.userNameCloud;
}
else{
CmdSetName(gplayAuth.userNameCloud);
}
LoadPlayerData();
}
}
public void SavePlayerData(){
#if UNITY_EDITOR
return;
#endif
FirebaseFirestore db = FirebaseFirestore.DefaultInstance;
//int playerCoin = int.Parse(coins.text);
Dictionary<string, object> saveValues = new Dictionary<string, object>{
{"playerInventory" , inventory.getInventoryDictionary()},
{"playerHealth" , health},
{"playerCoin", playerCoin},
{"killCount", enemyKillCount},
{"completedQuest", completedQuests},
};
DocumentReference docRef = db.Collection("PlayerData").Document(gplayAuth.userID);
docRef.SetAsync(saveValues).ContinueWithOnMainThread(task => {
if(task.IsCompleted){
Debug.Log("Save Completed Firestore");
}
else{
Debug.Log("Failed to save data to firestore");
}
});
}
public void LoadPlayerData(){
#if UNITY_EDITOR
return;
#endif
FirebaseFirestore db = FirebaseFirestore.DefaultInstance;
DocumentReference docRef = db.Collection("PlayerData").Document(gplayAuth.userID);
docRef.GetSnapshotAsync().ContinueWithOnMainThread(task => {
DocumentSnapshot snapshot = task.Result;
if(snapshot.Exists){
//load data
// Dictionary<string,object> dic = snapshot.ToDictionary(ServerTimestampBehavior.Estimate);
// Debug.Log("Reading data");
// foreach(KeyValuePair<string,object> item in dic){
// Debug.Log(item.Key + " : " +item.Value.ToString());
// }
//saveNameTxt.text = snapshot.GetValue<string>("playerName");
int _enemyKillCount = snapshot.GetValue<int>("killCount");
SetEnemyKillCount(_enemyKillCount);
//Load coin
int _playerCoin = snapshot.GetValue<int>("playerCoin");
SetPlayerCoins(_playerCoin);
// coinText.text = snapshot.GetValue<int>("playerCoin").ToString();
//Load Health
int savedHealth = snapshot.GetValue<int>("playerHealth");
SetHealth(savedHealth);
healthBar.SetHealth(savedHealth);
//load Inventory
Dictionary<string, int> inventoryGetData = snapshot.GetValue<Dictionary<string,int>>("playerInventory");
inventory.setInventoryData(inventoryGetData);
completedQuests = snapshot.GetValue<List<string>>("completedQuest");
}else{
//show error previous data doesnt exists to load
Debug.Log("No previous data to load");
}
});
}
void CmdSetName(string nameValue){
playerName = nameValue;
}
void OnDirectionChanged(Vector2 oldVal, Vector2 newVal){
character.SetDirection(newVal);
}
void OnAnimChanged(int oldVal, int newVal){
character.AnimationManager.SetState((CharacterState)newVal);
}
void Update(){
if(isLocalPlayer){
if(isServer){
SetAnimationData(character.Direction, character.Animator.GetInteger("State"));
}else{
CmdUpdateAnim(character.Direction, character.Animator.GetInteger("State"));
}
healthBar.SetHealth(health);
txtEnemyKillCount.text = enemyKillCount.ToString();
coinText.text = playerCoin.ToString();
txtPlayerName.text = gplayAuth.userNameCloud;
}
ShowXP();
ShowLevel();
}
[Command]
void CmdUpdateAnim(Vector2 direction, int animState){
SetAnimationData(direction, animState);
}
void SetAnimationData(Vector2 direction, int animState){
directionNetwork = direction;
animIntNetwork = animState;
if(!isLocalPlayer){
character.AnimationManager.SetState((CharacterState)animState);
character.SetDirection(direction);
}
}
void OnHealthChanged(int oldVal, int newVal){
if(!isLocalPlayer){return;}
//
if(oldVal < newVal){
GameObject newObject = Instantiate(healthVfx , character.characterTransform());
newObject.transform.localPosition = Vector3.zero;
newObject.transform.parent = transform;
//StartCoroutine (Couroutine_autoDisableVFX(newObject));
vfxScript vfxSc = newObject.AddComponent<vfxScript>();
}else if (oldVal > newVal ){
//damage VFX
GameObject newObject = Instantiate(damageVfx , character.characterTransform());
newObject.transform.localPosition = new Vector3(0, 5f, 0);
newObject.transform.parent = transform;
//StartCoroutine (Couroutine_autoDisableVFX(newObject));
vfxScript vfxSc = newObject.AddComponent<vfxScript>();
// vfxSc.offsetVFX = new Vector3(0, 5f, 0);
// vfxSc.target = character.characterTransform();
}
SavePlayerData();
healthBar.SetHealth(newVal);
}
// IEnumerator Couroutine_autoDisableVFX(GameObject go){
// yield return new WaitForSecondsRealtime(5f);
// Destroy(go);
// }
void onKillCountChange(int oldval, int newval){
if(!isLocalPlayer){return;}
int prevLevel = GetLevelForKills(oldval);
int newLevel = GetLevelForKills(newval);
SavePlayerData();
if(newLevel > prevLevel){
StartCoroutine(uiTxtDelay(25f));
}
if(enemyKillCount == 5 ){
//SavePlayerData();
//QuestComplete();
AddCoin();
}
}
public void SetHealth(int newvalue){
if(isServer){
health = newvalue;
healthBar.SetHealth(newvalue);
}else{
CmdSetHealth(newvalue);
}
}
public void SetEnemyKillCount(int newValue){
if(isServer){
enemyKillCount = newValue;
}else{
CmdSetEnemyKillCount(newValue);
}
}
public void SetPlayerCoins(int newVal){
if(isServer){
playerCoin = newVal;
}else{
CmdSetPlayerCoin(newVal);
}
}
[Command]
void CmdSetPlayerCoin(int newVal){
playerCoin = newVal;
}
[Command]
void CmdSetEnemyKillCount(int newValue){
enemyKillCount = newValue;
}
[Command]
void CmdSetHealth(int newValue){
health = newValue;
}
public void TakeDamage(int attackDamage){
serverTakeDmg(attackDamage);
// if(isLocalPlayer){
// takedmg(attackDamage);
// }else if(isServer){
// RpcTakeDamage(attackDamage);
// }
}
void serverTakeDmg(int damage){
health -= damage;
if(health <=0){
RpcDeath();
death();
}
}
public void ShowXP(){
xpText.text = xp.ToString();
}
public void ShowLevel(){
lvlText.text = lvl.ToString();
}
public void OnEnemyKilled(){
int prevValue = lvl;
// SavePlayerData();
enemyKillCount++;
}
IEnumerator uiTxtDelay (float delayTime){
//enable
xpEnableTxt.gameObject.SetActive(true);
attackDmgEnableTxt.gameObject.SetActive(true);
yield return new WaitForSecondsRealtime(delayTime);
//disable
xpEnableTxt.gameObject.SetActive(false);
attackDmgEnableTxt.gameObject.SetActive(false);
}
// public void QuestComplete(){
// //task completion logic
// // Strikethrough the text
// //questText.text = "<s>Kill 5 Enemies to claim 100Golds</s> Completed";
// Debug.Log("First quest completed");
// }
public void AddCoin(){
playerCoin += 100;
coinText.text = playerCoin.ToString();
}
[ClientRpc]
public void RpcDeath(){
death();
}
public bool isDead = false;
public void death(){
Debug.Log("Death called");
character.AnimationManager.Die();
isDead = true;
StartCoroutine(CouroutineWaitDeath());
// throw new System.Exception();
}
IEnumerator CouroutineWaitDeath (){
yield return new WaitForSecondsRealtime(3);
isDead = false;
playerRespawn();
}
public void OnAttack(){
if(isLocalPlayer){
PlayAttackAnim();
if(isServer){
RpcPlayAttackAnim();
}else{
CmdPlayAttackAnim();
}
}
}
[Command]
void CmdPlayAttackAnim(){
PlayAttackAnim();
RpcPlayAttackAnim();
}
[ClientRpc]
void RpcPlayAttackAnim(){
if(isLocalPlayer){return;}
PlayAttackAnim();
}
void PlayAttackAnim(){
switch (character.WeaponType)
{
case WeaponType.Melee1H:
case WeaponType.Paired:
character.AnimationManager.Slash(twoHanded: false);
break;
case WeaponType.Melee2H:
character.AnimationManager.Slash(twoHanded: true);
break;
case WeaponType.Bow:
character.AnimationManager.ShotBow();
break;
}
}
public void playerRespawn(){
Debug.Log("Respawning");
health=100;
healthBar.SetHealth(health);
character.AnimationManager.SetState(CharacterState.Idle);
Transform newSpawnLocationPlayer = GameManager.instance.spawnPointsPlayer.GetChild(Random.Range(0,GameManager.instance.spawnPointsPlayer.childCount));
transform.position = newSpawnLocationPlayer.position;
}
//Pickup
public void PickupObject(pickup item){
if(!isServer){ Debug.LogError("Cant call command on client, 403"); return; }
if(isLocalPlayer){
pickupObject(item.lootType);
}else{
RpcPickupObject(item.lootType);
}
}
[ClientRpc]
void RpcPickupObject(string type){
if(isLocalPlayer){
pickupObject(type);
}
}
void pickupObject(string type){
inventory.AddItem(type);
}
public void DropPickup(string type){
if(isServer){
GameManager.instance.SpawnPickup(type,transform.position + new Vector3(0.85f,0.6f));
}else{
CmdDropPickup(type);
}
}
[Command]
void CmdDropPickup(string type){
GameManager.instance.SpawnPickup(type,transform.position + new Vector3(4,0));
}
public void GoBackMenu(){
startClient.instance.networkManager.StopClient();
SceneManager.LoadScene("GameLogin");
PlayGamesPlatform.Instance.SignOut();
Firebase.Auth.FirebaseAuth.DefaultInstance.SignOut();
}
}