This commit is contained in:
Nim XD
2024-08-27 21:01:33 +05:30
parent 99eaf514fd
commit 121a1b7c73
31803 changed files with 623461 additions and 623399 deletions

Binary file not shown.

View File

@@ -1,125 +1,125 @@
using System;
using System.Collections;
using System.Collections.Generic;
using TMPro;
using UnityEngine;
using UnityEngine.UI;
public class Inventory : MonoBehaviour
{
public Transform inventorySlotsParent;
public InventoryItemsCollection lootData;
public InventoryManager inventoryManager;
playerNetwork playerNet;
void Awake(){
playerNet = GetComponent<playerNetwork>();
}
private void UseItem(int index){
if(playerNet.health >= 100){
return;
}
RemoveItem(lootData.items[index].type);
switch(lootData.items[index].type){
case "apple" :
playerNet.SetHealth(playerNet.health + 10 );
break;
case "potion" :
playerNet.SetHealth(playerNet.health + 35 );
break;
case "potion2" :
playerNet.SetHealth(playerNet.health + 25 );
break;
case "meat" :
playerNet.SetHealth(playerNet.health + 40 );
break;
case "strawberry" :
playerNet.SetHealth(playerNet.health + 5 );
break;
//
}
}
void DropItem(int index){
Debug.Log("Dropping item " + index);
if(RemoveItem(lootData.items[index].type)){
playerNet.DropPickup(lootData.items[index].type);
}else{
Debug.Log("No items to drop in slot " + index);
}
}
public void AddItem(string type){
inventoryManager.AddInvItem(type);
return;
foreach(item loot in lootData.items){
if(loot.type == type){
loot.count++;
break;
}
}
UpdateUI();
playerNet.SavePlayerData();
}
public bool RemoveItem(string type){
playerNet.SavePlayerData();
foreach(item loot in lootData.items){
if(loot.type == type){
if(loot.count <=0){return false;}
loot.count--;
break;
}
}
UpdateUI();
return true;
}
public int GetStock(string type){
int count =0;
foreach(item loot in lootData.items){
if(loot.type == type){
count = loot.count;
break;
}
}
UpdateUI();
return count;
}
public void UpdateUI(){
// for(int i =0; i < inventorySlotsParent.childCount; i++){
// Sprite chosenSprite = null;
// if(i < lootData.items.Length){
// chosenSprite= (lootData.items[i].count >0) ? lootData.items[i].image : null;
// }
// inventorySlotsParent.GetChild(i).GetChild(0).GetComponent<Image>().sprite = chosenSprite;
// inventorySlotsParent.GetChild(i).GetChild(0).gameObject.SetActive(chosenSprite != null);
// inventorySlotsParent.GetChild(i).GetChild(2).GetComponent<TMP_Text>().text = chosenSprite != null ? lootData.items[i].count.ToString() : "";
// }
}
}
[Serializable]
public class LootData{
public string type;
public Sprite image;
public GameObject prefab;
public int count;
public int spawnProbability = 50;
using System;
using System.Collections;
using System.Collections.Generic;
using TMPro;
using UnityEngine;
using UnityEngine.UI;
public class Inventory : MonoBehaviour
{
public Transform inventorySlotsParent;
public InventoryItemsCollection lootData;
public InventoryManager inventoryManager;
playerNetwork playerNet;
void Awake(){
playerNet = GetComponent<playerNetwork>();
}
private void UseItem(int index){
if(playerNet.health >= 100){
return;
}
RemoveItem(lootData.items[index].type);
switch(lootData.items[index].type){
case "apple" :
playerNet.SetHealth(playerNet.health + 10 );
break;
case "potion" :
playerNet.SetHealth(playerNet.health + 35 );
break;
case "potion2" :
playerNet.SetHealth(playerNet.health + 25 );
break;
case "meat" :
playerNet.SetHealth(playerNet.health + 40 );
break;
case "strawberry" :
playerNet.SetHealth(playerNet.health + 5 );
break;
//
}
}
void DropItem(int index){
Debug.Log("Dropping item " + index);
if(RemoveItem(lootData.items[index].type)){
playerNet.DropPickup(lootData.items[index].type);
}else{
Debug.Log("No items to drop in slot " + index);
}
}
public void AddItem(string type){
inventoryManager.AddInvItem(type);
return;
foreach(item loot in lootData.items){
if(loot.type == type){
loot.count++;
break;
}
}
UpdateUI();
playerNet.SavePlayerData();
}
public bool RemoveItem(string type){
playerNet.SavePlayerData();
foreach(item loot in lootData.items){
if(loot.type == type){
if(loot.count <=0){return false;}
loot.count--;
break;
}
}
UpdateUI();
return true;
}
public int GetStock(string type){
int count =0;
foreach(item loot in lootData.items){
if(loot.type == type){
count = loot.count;
break;
}
}
UpdateUI();
return count;
}
public void UpdateUI(){
// for(int i =0; i < inventorySlotsParent.childCount; i++){
// Sprite chosenSprite = null;
// if(i < lootData.items.Length){
// chosenSprite= (lootData.items[i].count >0) ? lootData.items[i].image : null;
// }
// inventorySlotsParent.GetChild(i).GetChild(0).GetComponent<Image>().sprite = chosenSprite;
// inventorySlotsParent.GetChild(i).GetChild(0).gameObject.SetActive(chosenSprite != null);
// inventorySlotsParent.GetChild(i).GetChild(2).GetComponent<TMP_Text>().text = chosenSprite != null ? lootData.items[i].count.ToString() : "";
// }
}
}
[Serializable]
public class LootData{
public string type;
public Sprite image;
public GameObject prefab;
public int count;
public int spawnProbability = 50;
}

View File

@@ -1,11 +1,11 @@
fileFormatVersion: 2
guid: 49c91741a6de5437a88e05174cb996c0
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
fileFormatVersion: 2
guid: 49c91741a6de5437a88e05174cb996c0
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -67,8 +67,9 @@ public class ItemInventory : MonoBehaviour, IBeginDragHandler, IDragHandler, IEn
public void OnPointerClick(PointerEventData eventData)
{
//inventoryManager.SelectItem(item);
//inventoryManager.SelectItem(item);
if (item.isUsable == false)return;
if (inventoryManager.UseItem(item))
{
Destroy(gameObject);

View File

@@ -8,7 +8,8 @@ using UnityEngine.UI;
public class item : ScriptableObject
{
public string type;
public Sprite image;
public bool isUsable;
public Sprite image;
public GameObject prefab;
public int count;
public int spawnProbability = 50;

View File

@@ -1,29 +1,29 @@
using System.Collections;
using System.Collections.Generic;
using TMPro;
using UnityEngine;
using UnityEngine.SceneManagement;
public class MenuSceneScript : MonoBehaviour
{
public TMP_Text usernameUI;
void Start()
{
}
void Update()
{
usernameUI.text = gplayAuth.userNameCloud;
}
public void LoadGameScene(){
SceneManager.LoadScene("Game");
}
public void LogoutBacktoLogin(){
SceneManager.LoadScene("GameLogin");
}
}
using System.Collections;
using System.Collections.Generic;
using TMPro;
using UnityEngine;
using UnityEngine.SceneManagement;
public class MenuSceneScript : MonoBehaviour
{
public TMP_Text usernameUI;
void Start()
{
}
void Update()
{
usernameUI.text = gplayAuth.userNameCloud;
}
public void LoadGameScene(){
SceneManager.LoadScene("Game");
}
public void LogoutBacktoLogin(){
SceneManager.LoadScene("GameLogin");
}
}

View File

@@ -1,11 +1,11 @@
fileFormatVersion: 2
guid: 18a59194b23514d06b81e36cef29eb11
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
fileFormatVersion: 2
guid: 18a59194b23514d06b81e36cef29eb11
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -1,141 +1,141 @@
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Mirror;
public class PlayerAttack : NetworkBehaviour{
public StatManager statManager;
private float timeBetweenAttacks;
public float startTimeBtwAttacks;
//public Transform attackPosition;
public LayerMask enemyMask;
public float attackRange;
public Vector3 castOffset;
public int damage;
public playerNetwork pnet;
public GameObject projectile;
public GameObject leftAnim,rightAnim,upAnim,downAnim;
void Awake(){
pnet.playerAttack = this;
}
void Start(){
if(!isLocalPlayer){
Destroy(this);
}else{
statManager.OnStatsChanged += onStatChange;
}
}
public void onStatChange(){
damage = statManager.GetEffectiveValue("strength");
}
// void Update(){
// //Get player look dir
// if(timeBetweenAttacks <=0){
// if(Input.GetMouseButtonDown(0)){
// StartCoroutine(couroutineAttack());
// timeBetweenAttacks = startTimeBtwAttacks;
// }
// }else{
// timeBetweenAttacks -= Time.deltaTime;
// }
// }
IEnumerator couroutineAttack(bool isMagical){
yield return new WaitForSecondsRealtime(0.6f);
Attack(isMagical);
}
public void Attack(bool isMagical){
if(pnet.health<=0){return;}
Vector3 direction = GetPlayerLookDir();
RaycastHit2D hit = Physics2D.Linecast(transform.position + castOffset, castOffset +transform.position + (direction * attackRange), enemyMask);
if(hit.collider == null){return;}
if(hit.collider.transform.GetComponent<enemyScript>() != null){
int damageamount = damage + (pnet.lvl*5);
if(isMagical){
hit.collider.transform.GetComponent<enemyScript>().TakeMagicalDamage(damageamount, netId);
}else{
hit.collider.transform.GetComponent<enemyScript>().TakeDamage(damageamount, netId);
}
Debug.Log("Attacked enemy " + damageamount);
}else{
Debug.Log("Not an enemy : " + hit.collider.transform.name);
}
}
public float magicalProjectileSpawnOffset = 1;
public void MagicalAttack(){
if(pnet.health<=0){return;}
Vector3 direction = GetPlayerLookDir();
//if(isServer){
pnet.MagicalAttack(direction, magicalProjectileSpawnOffset, damage);
/*}else{
Debug.Log(direction);
CmdMagicalAttack(direction);
}*/
}
/* [Command]
void CmdMagicalAttack(Vector3 direction){
magicalAttack(direction);
}*/
Vector3 GetPlayerLookDir(){
Vector3 direction = Vector3.right;
if(leftAnim.activeSelf){
direction = Vector3.left;
}else if(rightAnim.activeSelf){
direction = Vector3.right;
}else if(upAnim.activeSelf){
direction = Vector3.up;
}else if(downAnim.activeSelf){
direction = Vector3.down;
}
return direction;
}
void OnDrawGizmos(){
Gizmos.color = Color.red;
Gizmos.DrawLine(transform.position+castOffset, castOffset+ transform.position + (GetPlayerLookDir() * attackRange));
}
// void Update() {
// if(timeBetweenAttacks <= 0){
// if(Input.GetMouseButtonDown(0)){
// Collider2D[] enemyInRange = Physics2D.OverlapCircleAll(attackPosition.position , attackRange , enemyMask);
// for(int i = 0; i< enemyInRange.Length; i++ ){
// enemyInRange[i].GetComponent<enemyScript>().TakeDamage(damage);
// }
// }
// timeBetweenAttacks = startTimeBtwAttacks;
// }
// else{
// timeBetweenAttacks -= Time.deltaTime;
// }
// }
// void OnDrawGizmosSelected() {
// Gizmos.color = Color.red;
// Gizmos.DrawSphere(attackPosition.position, attackRange);
// }
}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Mirror;
public class PlayerAttack : NetworkBehaviour{
public StatManager statManager;
private float timeBetweenAttacks;
public float startTimeBtwAttacks;
//public Transform attackPosition;
public LayerMask enemyMask;
public float attackRange;
public Vector3 castOffset;
public int damage;
public playerNetwork pnet;
public GameObject projectile;
public GameObject leftAnim,rightAnim,upAnim,downAnim;
void Awake(){
pnet.playerAttack = this;
}
void Start(){
if(!isLocalPlayer){
Destroy(this);
}else{
statManager.OnStatsChanged += onStatChange;
}
}
public void onStatChange(){
damage = statManager.GetEffectiveValue("strength");
}
// void Update(){
// //Get player look dir
// if(timeBetweenAttacks <=0){
// if(Input.GetMouseButtonDown(0)){
// StartCoroutine(couroutineAttack());
// timeBetweenAttacks = startTimeBtwAttacks;
// }
// }else{
// timeBetweenAttacks -= Time.deltaTime;
// }
// }
IEnumerator couroutineAttack(bool isMagical){
yield return new WaitForSecondsRealtime(0.6f);
Attack(isMagical);
}
public void Attack(bool isMagical){
if(pnet.health<=0){return;}
Vector3 direction = GetPlayerLookDir();
RaycastHit2D hit = Physics2D.Linecast(transform.position + castOffset, castOffset +transform.position + (direction * attackRange), enemyMask);
if(hit.collider == null){return;}
if(hit.collider.transform.GetComponent<enemyScript>() != null){
int damageamount = damage + (pnet.lvl*5);
if(isMagical){
hit.collider.transform.GetComponent<enemyScript>().TakeMagicalDamage(damageamount, netId);
}else{
hit.collider.transform.GetComponent<enemyScript>().TakeDamage(damageamount, netId);
}
Debug.Log("Attacked enemy " + damageamount);
}else{
Debug.Log("Not an enemy : " + hit.collider.transform.name);
}
}
public float magicalProjectileSpawnOffset = 1;
public void MagicalAttack(){
if(pnet.health<=0){return;}
Vector3 direction = GetPlayerLookDir();
//if(isServer){
pnet.MagicalAttack(direction, magicalProjectileSpawnOffset, damage);
/*}else{
Debug.Log(direction);
CmdMagicalAttack(direction);
}*/
}
/* [Command]
void CmdMagicalAttack(Vector3 direction){
magicalAttack(direction);
}*/
Vector3 GetPlayerLookDir(){
Vector3 direction = Vector3.right;
if(leftAnim.activeSelf){
direction = Vector3.left;
}else if(rightAnim.activeSelf){
direction = Vector3.right;
}else if(upAnim.activeSelf){
direction = Vector3.up;
}else if(downAnim.activeSelf){
direction = Vector3.down;
}
return direction;
}
void OnDrawGizmos(){
Gizmos.color = Color.red;
Gizmos.DrawLine(transform.position+castOffset, castOffset+ transform.position + (GetPlayerLookDir() * attackRange));
}
// void Update() {
// if(timeBetweenAttacks <= 0){
// if(Input.GetMouseButtonDown(0)){
// Collider2D[] enemyInRange = Physics2D.OverlapCircleAll(attackPosition.position , attackRange , enemyMask);
// for(int i = 0; i< enemyInRange.Length; i++ ){
// enemyInRange[i].GetComponent<enemyScript>().TakeDamage(damage);
// }
// }
// timeBetweenAttacks = startTimeBtwAttacks;
// }
// else{
// timeBetweenAttacks -= Time.deltaTime;
// }
// }
// void OnDrawGizmosSelected() {
// Gizmos.color = Color.red;
// Gizmos.DrawSphere(attackPosition.position, attackRange);
// }
}

View File

@@ -1,11 +1,11 @@
fileFormatVersion: 2
guid: dfcdf5b454dfc443399497cbc65ab135
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
fileFormatVersion: 2
guid: dfcdf5b454dfc443399497cbc65ab135
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -1,43 +1,43 @@
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Events;
public class QuestAction : MonoBehaviour
{
public QuestScriptable questData;
bool isRegistered =false;
public UnityEvent OnComplete;
public bool isFinalAction = true;
private void OnTriggerEnter2D(Collider2D other) {
if(other.CompareTag("Player") && other.transform == playerNetwork.localPlayerTransform){
OnComplete.Invoke();
if(isFinalAction){
playerNetwork.localPlayerTransform.GetComponent<playerNetwork>().CompleteQuest(questData);
}
gameObject.SetActive(false);
}
}
public void activate(){
gameObject.SetActive(true);
}
void Update()
{
if(playerNetwork.localPlayerTransform != null && !isRegistered){
Register();
}
}
void Register(){
playerNetwork.registerQuestAction(this);
isRegistered = true;
gameObject.SetActive(false);
}
}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Events;
public class QuestAction : MonoBehaviour
{
public QuestScriptable questData;
bool isRegistered =false;
public UnityEvent OnComplete;
public bool isFinalAction = true;
private void OnTriggerEnter2D(Collider2D other) {
if(other.CompareTag("Player") && other.transform == playerNetwork.localPlayerTransform){
OnComplete.Invoke();
if(isFinalAction){
playerNetwork.localPlayerTransform.GetComponent<playerNetwork>().CompleteQuest(questData);
}
gameObject.SetActive(false);
}
}
public void activate(){
gameObject.SetActive(true);
}
void Update()
{
if(playerNetwork.localPlayerTransform != null && !isRegistered){
Register();
}
}
void Register(){
playerNetwork.registerQuestAction(this);
isRegistered = true;
gameObject.SetActive(false);
}
}

View File

@@ -1,11 +1,11 @@
fileFormatVersion: 2
guid: 4d02a12b490f54cdca519cc4e45b0fc4
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
fileFormatVersion: 2
guid: 4d02a12b490f54cdca519cc4e45b0fc4
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -1,13 +1,13 @@
using UnityEngine;
[CreateAssetMenu(fileName = "NewQuest", menuName = "ScriptableObjects/QuestData", order = 1)]
public class QuestScriptable : ScriptableObject
{
public string questName;
public string [] questLines;
public string questTitle;
public int rewardAmount = 1000;
using UnityEngine;
[CreateAssetMenu(fileName = "NewQuest", menuName = "ScriptableObjects/QuestData", order = 1)]
public class QuestScriptable : ScriptableObject
{
public string questName;
public string [] questLines;
public string questTitle;
public int rewardAmount = 1000;
}

View File

@@ -1,11 +1,11 @@
fileFormatVersion: 2
guid: bb4f7aac1a911412f89952ac827aabad
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
fileFormatVersion: 2
guid: bb4f7aac1a911412f89952ac827aabad
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -1,29 +1,29 @@
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class SpriteHealthBar : MonoBehaviour
{
private Vector3 startScale;
public Transform healthBarFill;
public float health;
void Awake()
{
startScale = healthBarFill.localScale;
}
public void SetHealth(float amount, float maxHealth = 100f){
if(maxHealth == 0 ){Debug.Log("max health is 0"); return;}
health = amount;
float amountMult = amount / maxHealth;
if(amountMult<0){amountMult=0;}
//Debug.Log($"Setting health on {transform.name}: {amount} / {maxHealth}");
healthBarFill.localScale = new Vector3(startScale.x * amountMult, startScale.y,startScale.z );
}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class SpriteHealthBar : MonoBehaviour
{
private Vector3 startScale;
public Transform healthBarFill;
public float health;
void Awake()
{
startScale = healthBarFill.localScale;
}
public void SetHealth(float amount, float maxHealth = 100f){
if(maxHealth == 0 ){Debug.Log("max health is 0"); return;}
health = amount;
float amountMult = amount / maxHealth;
if(amountMult<0){amountMult=0;}
//Debug.Log($"Setting health on {transform.name}: {amount} / {maxHealth}");
healthBarFill.localScale = new Vector3(startScale.x * amountMult, startScale.y,startScale.z );
}
}

View File

@@ -1,11 +1,11 @@
fileFormatVersion: 2
guid: f9895ab40a0ea421491e9fe5bc71dd24
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
fileFormatVersion: 2
guid: f9895ab40a0ea421491e9fe5bc71dd24
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -1,35 +1,35 @@
using System.Collections;
using System.Collections.Generic;
using Unity.VisualScripting;
using UnityEngine;
public class cameraRPG : MonoBehaviour
{
public static cameraRPG instance;
public Transform focus;
public float smoothTime = 2;
public Vector3 offset;
void Awake()
{
instance = this;
}
public void SetTarget(Transform target){
focus = target;
//offset = focus.position - transform.position;
}
public bool isPaused =false;
void Update()
{
if(focus == null){return;}
if(isPaused){return;}
transform.position = Vector3.Lerp(transform.position, focus.position - offset, Time.deltaTime * smoothTime);
}
public void Teleport(Vector3 newLocation){
transform.position = newLocation - offset;
}
}
using System.Collections;
using System.Collections.Generic;
using Unity.VisualScripting;
using UnityEngine;
public class cameraRPG : MonoBehaviour
{
public static cameraRPG instance;
public Transform focus;
public float smoothTime = 2;
public Vector3 offset;
void Awake()
{
instance = this;
}
public void SetTarget(Transform target){
focus = target;
//offset = focus.position - transform.position;
}
public bool isPaused =false;
void Update()
{
if(focus == null){return;}
if(isPaused){return;}
transform.position = Vector3.Lerp(transform.position, focus.position - offset, Time.deltaTime * smoothTime);
}
public void Teleport(Vector3 newLocation){
transform.position = newLocation - offset;
}
}

View File

@@ -1,11 +1,11 @@
fileFormatVersion: 2
guid: 0a957a08d3f1b4948b416a1e2c8227a2
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
fileFormatVersion: 2
guid: 0a957a08d3f1b4948b416a1e2c8227a2
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -1,18 +1,18 @@
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class enemyHealthBar : MonoBehaviour
{
public enemyScript enemy;
float timer=0;
void Update()
{
if(timer >=0){ timer -= Time.deltaTime; return;}
timer = 0.5f;
enemy.healthBar.SetHealth(enemy.health, enemy.maxHealth);
}
}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class enemyHealthBar : MonoBehaviour
{
public enemyScript enemy;
float timer=0;
void Update()
{
if(timer >=0){ timer -= Time.deltaTime; return;}
timer = 0.5f;
enemy.healthBar.SetHealth(enemy.health, enemy.maxHealth);
}
}

View File

@@ -1,11 +1,11 @@
fileFormatVersion: 2
guid: ccae36e0d0c894831b0480eabaf8d7e9
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
fileFormatVersion: 2
guid: ccae36e0d0c894831b0480eabaf8d7e9
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -1,436 +1,436 @@
using System.Collections;
using UnityEngine;
using Spine.Unity;
using Spine.Unity.Examples;
using Mirror;
public class enemyScript : NetworkBehaviour
{
public const int HEALTH_INC = 2;
public const float DAMAGE_INC = 1.2f;
public const float XP_GAIN = 1.5f;
public const int XP_GAIN_Base = 5;
[SyncVar(hook = nameof(OnHealthChange))]
public int health;
[SyncVar(hook = nameof(OnMagicalHealthChange))]
public int magicalHealth;
public SpriteHealthBar healthBar;
public SpriteHealthBar MagicalhealthBar;
public float speed;
public float chaseRadius;
public float attackRadius;
public bool rotate;
//public LayerMask layerMask;
public playerNetwork target;
private Rigidbody2D rb2;
public SkeletonAnimation animator;
private Vector2 movement;
public Vector3 dir;
public TextMesh enemyName;
public TextMesh enemyLevel;
public bool isInChaseRange;
public bool isInAttackRange;
public Transform uiEnemy;
public int enemyAttackDamage = 10;
MeshRenderer meshRenderer;
public GameObject hitVfx;
void Awake(){
meshRenderer = GetComponent<MeshRenderer>();
scanCooldown = Random.Range(0.5f, 1.5f);
}
private void Start(){
rb2 = GetComponent<Rigidbody2D>();
//target = GameObject.FindWithTag("Player").transform;
UpdateAnimation(directionString,animationString);
defaultPos = transform.position;
}
[SyncVar(hook =nameof(OnLevelChanged))]
public int level;
void OnLevelChanged(int oldVal, int newVal){
if(isServer){return;}
SetLevel(newVal);
}
public void SetLevel(int _level){
if(enemyLevel != null){
enemyLevel.text = _level.ToString();
}
level = _level;
int healthIncrement =level * HEALTH_INC;
maxHealth = 100 + healthIncrement;
health = (int)maxHealth;
magicalHealth = (int)maxHealth;
enemyAttackDamage += (int)(level * DAMAGE_INC);
// Debug.Log($"{health}/{maxHealth}");
}
public Vector3 defScale;
Vector3 defaultPos;
float playerDistCheckTimer=0f;
void LateUpdate(){
LOD();
}
public const float disappearDistFromPlayer = 15f;
void LOD(){
if(playerDistCheckTimer > 0){playerDistCheckTimer -= Time.deltaTime;return;}
playerDistCheckTimer = Random.Range(1.5f,2.5f);
if(playerNetwork.localPlayerTransform == null){return;}
float distToPlayer = Vector3.Distance(playerNetwork.localPlayerTransform.position, transform.position);
meshRenderer.enabled = distToPlayer < disappearDistFromPlayer;
}
#if UNITY_SERVER || UNITY_EDITOR
[Server]
private void Update(){
// animator.skeleton.SetSkin
// set animation state to running if in chase Range
//isInChaseRange = true
// isInChaseRange = Physics2D.OverlapCircle(transform.position, chaseRadius , layerMask);
// isInAttackRange = Physics2D.OverlapCircle(transform.position, attackRadius, layerMask);
if (health <= 0 ){
return;
}
if(target != null){
isInChaseRange = Vector3.Distance(transform.position, target.transform.position) < chaseRadius;
isInAttackRange = Vector3.Distance(transform.position, target.transform.position) < attackRadius;
}else{
isInChaseRange = false;
isInAttackRange = false;
}
ScanPlayers();
if(target !=null){
enemyFollow();
}
}
#endif
float scanTimer =0;
float scanCooldown;
public void ScanPlayers(){
if(scanTimer >0){scanTimer-=Time.deltaTime; return;}
scanTimer = scanCooldown;
playerNetwork[] playersinNetwork = FindObjectsOfType<playerNetwork>();
float closestDist = float.MaxValue;
playerNetwork closestPlayer = null;
foreach(playerNetwork player in playersinNetwork ){
if(player.health <= 0 ){continue;}
float dist = Vector3.Distance(transform.position, player.transform.position);
if(dist < closestDist){
closestPlayer = player;
closestDist = dist;
}
}
if(closestDist < chaseRadius){
target = closestPlayer ;
}
else {
target = null;
}
//if(target == null) {return;}
}
// [ClientRpc]
// void RpcUpdateAnim(string animDir , string animName, bool isLoop){
// UpdateAnimation(animDir , animName, isLoop);
// }
[SyncVar(hook =nameof(OnFlipped))]
bool isFlipped= false;
void OnFlipped(bool oldVal, bool newVal){
if(isServer){return;}
transform.localScale = new Vector3(defScale.x * (newVal ? -1 : 1),defScale.y,defScale.z);
HandleFlip();
}
void HandleFlip(){
if(uiEnemy == null){
return;
}
if(transform.localScale.x < 0 ){
uiEnemy.localScale = new Vector3(-1,1,1);
}
else{
uiEnemy.localScale = new Vector3(1,1,1);
}
}
private void enemyFollow(){
if(Mathf.Abs(dir.y) > Mathf.Abs(dir.x)){
if(dir.y < 0){
directionString = "Back";
}else{
directionString = "Front";
}
}else{
directionString = "Side";
if(dir.x < 0){
transform.localScale = new Vector3(defScale.x,defScale.y,0);
isFlipped=false;
}else{
transform.localScale = new Vector3(-defScale.x,defScale.y,0);
isFlipped = true;
}
HandleFlip();
}
if(animationHistory != directionString + animationString){
UpdateAnimation(directionString, animationString);
// RpcUpdateAnim(directionString, animationString,true);
}
animationHistory=directionString + animationString;
if(target != null){
dir = transform.position - target.transform.position;
}
float angle = Mathf.Atan2(dir.y , dir.x ) * Mathf.Rad2Deg;
dir.Normalize();
movement = dir;
if(rotate){
//set anim direction x, y dir
}
}
string animationHistory ="";
[SyncVar(hook =nameof(OnAnimationDirectionChanged))]
public string directionString = "Side";
[SyncVar(hook =nameof(OnAnimationNameChanged))]
public string animationString = "Idle";
void OnAnimationDirectionChanged(string oldVal, string newVal){
UpdateAnimation(newVal, animationString);
}
void OnAnimationNameChanged(string oldVal, string newVal){
UpdateAnimation(directionString, newVal);
}
float attackTimer = 0f;
float attackDuration = 1.4f;
[SyncVar]
public float maxHealth;
#if UNITY_SERVER || UNITY_EDITOR
[Server]
private void FixedUpdate() {
if (health <= 0 || magicalHealth <= 0){
return;
}
healthBar.SetHealth(health, maxHealth);
MagicalhealthBar.SetHealth(magicalHealth, maxHealth); //magical health maxout err
if(isInChaseRange && !isInAttackRange ){
MoveEnemy(movement);
//Set animation to moving
animationString = "Walk";
}
if(isInAttackRange){
rb2.velocity = Vector2.zero;
//Set animation to attack
animationString = "Attack";
if(attackTimer < attackDuration){
attackTimer += Time.deltaTime;
}else{
attackTimer = 0 ;
Attack();
}
//TODO: ATTACK HERE
}
if(!isInAttackRange && !isInChaseRange){
//SetAnimation to idle
animationString = "Idle";
}
}
#endif
public void Attack(){
target.TakeDamage(enemyAttackDamage);
}
private void MoveEnemy(Vector2 dir){
rb2.MovePosition((Vector2)transform.position + (dir * speed * Time.deltaTime));
}
void UpdateAnimation(string direction, string animationName){
// try{
StartCoroutine(CoroutineUpdateAnim(direction, animationName));
}
IEnumerator CoroutineUpdateAnim(string direction, string animationName){
while(animator == null){
yield return new WaitForSeconds(0.1f);
Debug.LogError("animator is null!");
}
while(animator.skeleton == null){
yield return new WaitForSeconds(0.1f);
Debug.LogError("animator skelton is null!");
}
while(animator.AnimationState == null){
yield return new WaitForSeconds(0.1f);
Debug.LogError("animator state is null!");
}
animator.skeleton.SetSkin(direction);
animator.skeleton.SetSlotsToSetupPose();
animator.AnimationState.SetAnimation(0, $"{direction}_{animationName}", !animationName.ToLower().Contains("death"));
// }catch(Exception e){
// Debug.LogError(e.ToString());
// }
Debug.Log($"Updating enemy animation {direction}_{animationName}");
}
[Command(requiresAuthority =false)]
void CmdTakeDamage(int damage,uint id){
takedmg(damage,id);
Debug.Log("Enemy Attack Recieved ");
}
public void TakeDamage(int damage, uint id){
if(isServer){
takedmg(damage,id);
}
else{
CmdTakeDamage(damage,id);
}
}
void takedmg(int damage,uint id){
if(health<=0){return;}
health -= damage;
//hit vfx
// GameObject newObject = Instantiate(hitVfx , transform.position , Quaternion.identity );
// newObject.transform.localPosition = Vector3.zero;
// newObject.transform.parent = transform;
if(health<= 0 ){
StartCoroutine(couroutineDeath());
foreach(playerNetwork player in FindObjectsOfType<playerNetwork>()){
if(player.netId == id){
//This one attacked me
player.OnEnemyKilled(level);
}
}
}
Debug.Log("Enemy Takes Damage ***");
}
[Command(requiresAuthority =false)]
void CmdTakeMagicalDamage(int damage,uint id){
takeMagicalDmg(damage,id);
Debug.Log("Enemy Attack Recieved ");
}
public void TakeMagicalDamage(int damage, uint id){
if(isServer){
takeMagicalDmg(damage,id);
}
else{
CmdTakeMagicalDamage(damage,id);
}
}
void takeMagicalDmg(int damage,uint id){
if(magicalHealth<=0){return;}
magicalHealth -= damage;
if(magicalHealth<= 0 ){
StartCoroutine(couroutineDeath());
foreach(playerNetwork player in FindObjectsOfType<playerNetwork>()){
if(player.netId == id){
//This one attacked me
player.OnEnemyKilled(level);
}
}
}
Debug.Log("Enemy Takes Damage ***");
}
IEnumerator couroutineDeath(){
animationString = "Death";
UpdateAnimation(directionString , animationString);
// RpcUpdateAnim(directionString, animationString,false);
Vector3 lootSpawnPos = transform.position;
lootSpawnPos.z = GameManager.instance.LootSpawnPointsParent.GetChild(0).position.z;
//instantiate loot item
GameObject newLoot = Instantiate(GameManager.instance.GetRandomLoot(), lootSpawnPos, Quaternion.identity);
NetworkServer.Spawn(newLoot);
yield return new WaitForSecondsRealtime(5);
if (!isServer)
{
CmdDie();
}
else
{
GameManager.OnEnemyDeath(this, defaultPos);
}
/* transform.position = defaultPos;
health = (int)maxHealth;
magicalHealth = (int)maxHealth;*/
//animationString = "Idle";
}
[Command]
void CmdDie()
{
GameManager.OnEnemyDeath(this,defaultPos);
}
public void OnHealthChange(int oldVlaue, int newValue){
healthBar.SetHealth(newValue,maxHealth);
}
public void OnMagicalHealthChange(int oldVlaue, int newValue){
MagicalhealthBar.SetHealth(newValue,maxHealth);
}
using System.Collections;
using UnityEngine;
using Spine.Unity;
using Spine.Unity.Examples;
using Mirror;
public class enemyScript : NetworkBehaviour
{
public const int HEALTH_INC = 2;
public const float DAMAGE_INC = 1.2f;
public const float XP_GAIN = 1.5f;
public const int XP_GAIN_Base = 5;
[SyncVar(hook = nameof(OnHealthChange))]
public int health;
[SyncVar(hook = nameof(OnMagicalHealthChange))]
public int magicalHealth;
public SpriteHealthBar healthBar;
public SpriteHealthBar MagicalhealthBar;
public float speed;
public float chaseRadius;
public float attackRadius;
public bool rotate;
//public LayerMask layerMask;
public playerNetwork target;
private Rigidbody2D rb2;
public SkeletonAnimation animator;
private Vector2 movement;
public Vector3 dir;
public TextMesh enemyName;
public TextMesh enemyLevel;
public bool isInChaseRange;
public bool isInAttackRange;
public Transform uiEnemy;
public int enemyAttackDamage = 10;
MeshRenderer meshRenderer;
public GameObject hitVfx;
void Awake(){
meshRenderer = GetComponent<MeshRenderer>();
scanCooldown = Random.Range(0.5f, 1.5f);
}
private void Start(){
rb2 = GetComponent<Rigidbody2D>();
//target = GameObject.FindWithTag("Player").transform;
UpdateAnimation(directionString,animationString);
defaultPos = transform.position;
}
[SyncVar(hook =nameof(OnLevelChanged))]
public int level;
void OnLevelChanged(int oldVal, int newVal){
if(isServer){return;}
SetLevel(newVal);
}
public void SetLevel(int _level){
if(enemyLevel != null){
enemyLevel.text = _level.ToString();
}
level = _level;
int healthIncrement =level * HEALTH_INC;
maxHealth = 100 + healthIncrement;
health = (int)maxHealth;
magicalHealth = (int)maxHealth;
enemyAttackDamage += (int)(level * DAMAGE_INC);
// Debug.Log($"{health}/{maxHealth}");
}
public Vector3 defScale;
Vector3 defaultPos;
float playerDistCheckTimer=0f;
void LateUpdate(){
LOD();
}
public const float disappearDistFromPlayer = 15f;
void LOD(){
if(playerDistCheckTimer > 0){playerDistCheckTimer -= Time.deltaTime;return;}
playerDistCheckTimer = Random.Range(1.5f,2.5f);
if(playerNetwork.localPlayerTransform == null){return;}
float distToPlayer = Vector3.Distance(playerNetwork.localPlayerTransform.position, transform.position);
meshRenderer.enabled = distToPlayer < disappearDistFromPlayer;
}
#if UNITY_SERVER || UNITY_EDITOR
[Server]
private void Update(){
// animator.skeleton.SetSkin
// set animation state to running if in chase Range
//isInChaseRange = true
// isInChaseRange = Physics2D.OverlapCircle(transform.position, chaseRadius , layerMask);
// isInAttackRange = Physics2D.OverlapCircle(transform.position, attackRadius, layerMask);
if (health <= 0 ){
return;
}
if(target != null){
isInChaseRange = Vector3.Distance(transform.position, target.transform.position) < chaseRadius;
isInAttackRange = Vector3.Distance(transform.position, target.transform.position) < attackRadius;
}else{
isInChaseRange = false;
isInAttackRange = false;
}
ScanPlayers();
if(target !=null){
enemyFollow();
}
}
#endif
float scanTimer =0;
float scanCooldown;
public void ScanPlayers(){
if(scanTimer >0){scanTimer-=Time.deltaTime; return;}
scanTimer = scanCooldown;
playerNetwork[] playersinNetwork = FindObjectsOfType<playerNetwork>();
float closestDist = float.MaxValue;
playerNetwork closestPlayer = null;
foreach(playerNetwork player in playersinNetwork ){
if(player.health <= 0 ){continue;}
float dist = Vector3.Distance(transform.position, player.transform.position);
if(dist < closestDist){
closestPlayer = player;
closestDist = dist;
}
}
if(closestDist < chaseRadius){
target = closestPlayer ;
}
else {
target = null;
}
//if(target == null) {return;}
}
// [ClientRpc]
// void RpcUpdateAnim(string animDir , string animName, bool isLoop){
// UpdateAnimation(animDir , animName, isLoop);
// }
[SyncVar(hook =nameof(OnFlipped))]
bool isFlipped= false;
void OnFlipped(bool oldVal, bool newVal){
if(isServer){return;}
transform.localScale = new Vector3(defScale.x * (newVal ? -1 : 1),defScale.y,defScale.z);
HandleFlip();
}
void HandleFlip(){
if(uiEnemy == null){
return;
}
if(transform.localScale.x < 0 ){
uiEnemy.localScale = new Vector3(-1,1,1);
}
else{
uiEnemy.localScale = new Vector3(1,1,1);
}
}
private void enemyFollow(){
if(Mathf.Abs(dir.y) > Mathf.Abs(dir.x)){
if(dir.y < 0){
directionString = "Back";
}else{
directionString = "Front";
}
}else{
directionString = "Side";
if(dir.x < 0){
transform.localScale = new Vector3(defScale.x,defScale.y,0);
isFlipped=false;
}else{
transform.localScale = new Vector3(-defScale.x,defScale.y,0);
isFlipped = true;
}
HandleFlip();
}
if(animationHistory != directionString + animationString){
UpdateAnimation(directionString, animationString);
// RpcUpdateAnim(directionString, animationString,true);
}
animationHistory=directionString + animationString;
if(target != null){
dir = transform.position - target.transform.position;
}
float angle = Mathf.Atan2(dir.y , dir.x ) * Mathf.Rad2Deg;
dir.Normalize();
movement = dir;
if(rotate){
//set anim direction x, y dir
}
}
string animationHistory ="";
[SyncVar(hook =nameof(OnAnimationDirectionChanged))]
public string directionString = "Side";
[SyncVar(hook =nameof(OnAnimationNameChanged))]
public string animationString = "Idle";
void OnAnimationDirectionChanged(string oldVal, string newVal){
UpdateAnimation(newVal, animationString);
}
void OnAnimationNameChanged(string oldVal, string newVal){
UpdateAnimation(directionString, newVal);
}
float attackTimer = 0f;
float attackDuration = 1.4f;
[SyncVar]
public float maxHealth;
#if UNITY_SERVER || UNITY_EDITOR
[Server]
private void FixedUpdate() {
if (health <= 0 || magicalHealth <= 0){
return;
}
healthBar.SetHealth(health, maxHealth);
MagicalhealthBar.SetHealth(magicalHealth, maxHealth); //magical health maxout err
if(isInChaseRange && !isInAttackRange ){
MoveEnemy(movement);
//Set animation to moving
animationString = "Walk";
}
if(isInAttackRange){
rb2.velocity = Vector2.zero;
//Set animation to attack
animationString = "Attack";
if(attackTimer < attackDuration){
attackTimer += Time.deltaTime;
}else{
attackTimer = 0 ;
Attack();
}
//TODO: ATTACK HERE
}
if(!isInAttackRange && !isInChaseRange){
//SetAnimation to idle
animationString = "Idle";
}
}
#endif
public void Attack(){
target.TakeDamage(enemyAttackDamage);
}
private void MoveEnemy(Vector2 dir){
rb2.MovePosition((Vector2)transform.position + (dir * speed * Time.deltaTime));
}
void UpdateAnimation(string direction, string animationName){
// try{
StartCoroutine(CoroutineUpdateAnim(direction, animationName));
}
IEnumerator CoroutineUpdateAnim(string direction, string animationName){
while(animator == null){
yield return new WaitForSeconds(0.1f);
Debug.LogError("animator is null!");
}
while(animator.skeleton == null){
yield return new WaitForSeconds(0.1f);
Debug.LogError("animator skelton is null!");
}
while(animator.AnimationState == null){
yield return new WaitForSeconds(0.1f);
Debug.LogError("animator state is null!");
}
animator.skeleton.SetSkin(direction);
animator.skeleton.SetSlotsToSetupPose();
animator.AnimationState.SetAnimation(0, $"{direction}_{animationName}", !animationName.ToLower().Contains("death"));
// }catch(Exception e){
// Debug.LogError(e.ToString());
// }
Debug.Log($"Updating enemy animation {direction}_{animationName}");
}
[Command(requiresAuthority =false)]
void CmdTakeDamage(int damage,uint id){
takedmg(damage,id);
Debug.Log("Enemy Attack Recieved ");
}
public void TakeDamage(int damage, uint id){
if(isServer){
takedmg(damage,id);
}
else{
CmdTakeDamage(damage,id);
}
}
void takedmg(int damage,uint id){
if(health<=0){return;}
health -= damage;
//hit vfx
// GameObject newObject = Instantiate(hitVfx , transform.position , Quaternion.identity );
// newObject.transform.localPosition = Vector3.zero;
// newObject.transform.parent = transform;
if(health<= 0 ){
StartCoroutine(couroutineDeath());
foreach(playerNetwork player in FindObjectsOfType<playerNetwork>()){
if(player.netId == id){
//This one attacked me
player.OnEnemyKilled(level);
}
}
}
Debug.Log("Enemy Takes Damage ***");
}
[Command(requiresAuthority =false)]
void CmdTakeMagicalDamage(int damage,uint id){
takeMagicalDmg(damage,id);
Debug.Log("Enemy Attack Recieved ");
}
public void TakeMagicalDamage(int damage, uint id){
if(isServer){
takeMagicalDmg(damage,id);
}
else{
CmdTakeMagicalDamage(damage,id);
}
}
void takeMagicalDmg(int damage,uint id){
if(magicalHealth<=0){return;}
magicalHealth -= damage;
if(magicalHealth<= 0 ){
StartCoroutine(couroutineDeath());
foreach(playerNetwork player in FindObjectsOfType<playerNetwork>()){
if(player.netId == id){
//This one attacked me
player.OnEnemyKilled(level);
}
}
}
Debug.Log("Enemy Takes Damage ***");
}
IEnumerator couroutineDeath(){
animationString = "Death";
UpdateAnimation(directionString , animationString);
// RpcUpdateAnim(directionString, animationString,false);
Vector3 lootSpawnPos = transform.position;
lootSpawnPos.z = GameManager.instance.LootSpawnPointsParent.GetChild(0).position.z;
//instantiate loot item
GameObject newLoot = Instantiate(GameManager.instance.GetRandomLoot(), lootSpawnPos, Quaternion.identity);
NetworkServer.Spawn(newLoot);
yield return new WaitForSecondsRealtime(5);
if (!isServer)
{
CmdDie();
}
else
{
GameManager.OnEnemyDeath(this, defaultPos);
}
/* transform.position = defaultPos;
health = (int)maxHealth;
magicalHealth = (int)maxHealth;*/
//animationString = "Idle";
}
[Command]
void CmdDie()
{
GameManager.OnEnemyDeath(this,defaultPos);
}
public void OnHealthChange(int oldVlaue, int newValue){
healthBar.SetHealth(newValue,maxHealth);
}
public void OnMagicalHealthChange(int oldVlaue, int newValue){
MagicalhealthBar.SetHealth(newValue,maxHealth);
}
}

View File

@@ -1,11 +1,11 @@
fileFormatVersion: 2
guid: baf896ad3d2754898ad2dada2cf54758
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
fileFormatVersion: 2
guid: baf896ad3d2754898ad2dada2cf54758
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -1,247 +1,247 @@
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using GooglePlayGames;
using GooglePlayGames.BasicApi;
using UnityEngine.SocialPlatforms;
using System.Threading;
using UnityEngine.UI;
using Firebase.Firestore;
using Firebase.Extensions;
using System;
using UnityEngine.Networking;
using System.Text.RegularExpressions;
using TMPro;
using UnityEngine.SceneManagement;
public class gplayAuth : MonoBehaviour{
public TMP_Text gplayText;
public TMP_Text firebaseStatText;
public string AuthCode;
public static string userID;
bool IsConnected;
public TMP_InputField saveName, coins, item1, item2, item3 ;
public TMP_Text saveStatText;
public static string userNameCloud;
public TMP_Text saveNameTxt , coinsTxt, item1Txt, item2Txt, item3Txt;
#if UNITY_ANDROID
void Start() {
IsConnected =false;
PlayGamesClientConfiguration config = new PlayGamesClientConfiguration.Builder().RequestServerAuthCode(false)
.RequestEmail().RequestIdToken().EnableSavedGames().Build();
PlayGamesPlatform.InitializeInstance(config);
PlayGamesPlatform.DebugLogEnabled = true;
PlayGamesPlatform.Activate();
//GPGSLogin();
}
public void GPGSLogin(){
PlayGamesPlatform.Instance.Authenticate((success) => {
if(success == true){
//logged into Google Play Games
gplayText.text = "G-Play Connected";
Firebase.FirebaseApp.CheckAndFixDependenciesAsync().ContinueWithOnMainThread(task => {
if(task.Result == Firebase.DependencyStatus.Available){
//no dependency issue with firebase, continue to login
ConnectToFirebase();
}
else{
//error with firebase Dependecies plugin
firebaseStatText.text = "Dependency Error";
}
}
);
}
else{
Debug.LogError("Gplay failed");
}
}
);
}
public void SaveData(){
//checking if connected to firebase
if(IsConnected){
FirebaseFirestore db = FirebaseFirestore.DefaultInstance;
string playerName = saveName.text;
int playerCoin = int.Parse(coins.text);
List<string> plyaerInventoryItems = new List<string>();
plyaerInventoryItems.Add(item1.text);
plyaerInventoryItems.Add(item2.text);
plyaerInventoryItems.Add(item3.text);
Dictionary<string, object> saveValues = new Dictionary<string, object>{
{"playerName" , playerName},
{"playerCoin" , playerCoin},
{"playerInventory" , plyaerInventoryItems},
};
DocumentReference docRef = db.Collection("PlayerData").Document(userID);
docRef.SetAsync(saveValues).ContinueWithOnMainThread(task => {
if(task.IsCompleted){
saveStatText.text = "Save Completed Firestore";
}
else{
saveStatText.text = "Failed to save data to firestore";
}
});
}else{
//firebase_Not_Connected_error
Debug.LogError("firebase Not connected to save");
}
}
public void LoadData(){
if(IsConnected){
FirebaseFirestore db = FirebaseFirestore.DefaultInstance;
DocumentReference docRef = db.Collection("PlayerData").Document(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");
coinsTxt.text = snapshot.GetValue<int>("playerCoin").ToString();
List<string> inventoryList = snapshot.GetValue<List<string>>("playerInventory");
item1Txt.text = inventoryList[0];
item2Txt.text = inventoryList[1];
item3Txt.text = inventoryList[2];
}else{
//show error previous data doesnt exists to load
Debug.Log("No previous data to load");
}
});
}
}
public TMP_InputField registerEmail, registerPassword;
public void RegisterUser(){
Firebase.Auth.FirebaseAuth auth = Firebase.Auth.FirebaseAuth.DefaultInstance;
auth.CreateUserWithEmailAndPasswordAsync(registerEmail.text, registerPassword.text).ContinueWith(task => {
if (task.IsCanceled) {
Debug.LogError("CreateUserWithEmailAndPasswordAsync was canceled.");
return;
}
if (task.IsFaulted) {
Debug.LogError("CreateUserWithEmailAndPasswordAsync encountered an error: " + task.Exception);
return;
}
// Firebase user has been created.
Firebase.Auth.AuthResult result = task.Result;
Debug.LogFormat("Firebase user created successfully: {0} ({1})",
result.User.DisplayName, result.User.UserId);
OnAuthSuccess(result.User);
userNameCloud = registerEmail.text;
});
}
public TMP_InputField loginEmail, loginPassword;
public void LoginUser(){
Firebase.Auth.FirebaseAuth auth = Firebase.Auth.FirebaseAuth.DefaultInstance;
auth.SignInWithEmailAndPasswordAsync(loginEmail.text, loginPassword.text).ContinueWith(task => {
if (task.IsCanceled) {
Debug.LogError("SignInWithEmailAndPasswordAsync was canceled.");
return;
}
if (task.IsFaulted) {
Debug.LogError("SignInWithEmailAndPasswordAsync encountered an error: " + task.Exception);
return;
}
Firebase.Auth.AuthResult result = task.Result;
Debug.LogFormat("User signed in successfully: {0} ({1})",
result.User.DisplayName, result.User.UserId);
OnAuthSuccess(result.User);
userNameCloud = loginEmail.text;
});
}
void ConnectToFirebase(){
AuthCode=PlayGamesPlatform.Instance.GetServerAuthCode();
Debug.Log("Gplay auth " + AuthCode);
Firebase.Auth.FirebaseAuth FBAuth = Firebase.Auth.FirebaseAuth.DefaultInstance;
Firebase.Auth.Credential FBCred = Firebase.Auth.PlayGamesAuthProvider.GetCredential(AuthCode);
FBAuth.SignInWithCredentialAsync(FBCred).ContinueWithOnMainThread(task => {
if(task.IsCanceled){
firebaseStatText.text = "sign in cancelled";
}
if(task.IsFaulted){
firebaseStatText.text = "Error:"+task.Result;
}
Firebase.Auth.FirebaseUser user = FBAuth.CurrentUser;
if(user != null){
// userID = user.UserId;
// firebaseStatText.text = "Signed in As :"+ user.DisplayName;
// IsConnected = true;
OnAuthSuccess(user);
userNameCloud = user.DisplayName;
}
else{
//error getting username
}
});
// PlayGamesPlatform.Instance.RequestServerSideAccess(true , code => {
// AuthCode = code;
// Firebase.Auth.FirebaseAuth FBAuth = Firebase.Auth.FirebaseAuth.DefaultInstance;
// Firebase.Auth.Credential FBCred = Firebase.Auth.PlayGamesAuthProvider.GetCredential(AuthCode);
// FBAuth.SignInWithCredentialAsync(FBCred).ContinueWithOnMainThread(task => {
// if(task.IsCanceled){
// firebaseStatText.text = "sign in cancelled";
// }
// if(task.IsFaulted){
// firebaseStatText.text = "Error:"+task.Result;
// }
// Firebase.Auth.FirebaseUser user = FBAuth.CurrentUser;
// if(user != null){
// firebaseStatText.text = "Signed in As :"+ user.DisplayName;
// }
// else{
// //error getting username
// }
// });
// });
}
public void OnAuthSuccess(Firebase.Auth.FirebaseUser user){
userID = user.UserId;
firebaseStatText.text = "Signed in As :"+ user.DisplayName;
IsConnected = true;
//load game scene
SceneManager.LoadScene("MenuScene");
}
#endif
}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using GooglePlayGames;
using GooglePlayGames.BasicApi;
using UnityEngine.SocialPlatforms;
using System.Threading;
using UnityEngine.UI;
using Firebase.Firestore;
using Firebase.Extensions;
using System;
using UnityEngine.Networking;
using System.Text.RegularExpressions;
using TMPro;
using UnityEngine.SceneManagement;
public class gplayAuth : MonoBehaviour{
public TMP_Text gplayText;
public TMP_Text firebaseStatText;
public string AuthCode;
public static string userID;
bool IsConnected;
public TMP_InputField saveName, coins, item1, item2, item3 ;
public TMP_Text saveStatText;
public static string userNameCloud;
public TMP_Text saveNameTxt , coinsTxt, item1Txt, item2Txt, item3Txt;
#if UNITY_ANDROID
void Start() {
IsConnected =false;
PlayGamesClientConfiguration config = new PlayGamesClientConfiguration.Builder().RequestServerAuthCode(false)
.RequestEmail().RequestIdToken().EnableSavedGames().Build();
PlayGamesPlatform.InitializeInstance(config);
PlayGamesPlatform.DebugLogEnabled = true;
PlayGamesPlatform.Activate();
//GPGSLogin();
}
public void GPGSLogin(){
PlayGamesPlatform.Instance.Authenticate((success) => {
if(success == true){
//logged into Google Play Games
gplayText.text = "G-Play Connected";
Firebase.FirebaseApp.CheckAndFixDependenciesAsync().ContinueWithOnMainThread(task => {
if(task.Result == Firebase.DependencyStatus.Available){
//no dependency issue with firebase, continue to login
ConnectToFirebase();
}
else{
//error with firebase Dependecies plugin
firebaseStatText.text = "Dependency Error";
}
}
);
}
else{
Debug.LogError("Gplay failed");
}
}
);
}
public void SaveData(){
//checking if connected to firebase
if(IsConnected){
FirebaseFirestore db = FirebaseFirestore.DefaultInstance;
string playerName = saveName.text;
int playerCoin = int.Parse(coins.text);
List<string> plyaerInventoryItems = new List<string>();
plyaerInventoryItems.Add(item1.text);
plyaerInventoryItems.Add(item2.text);
plyaerInventoryItems.Add(item3.text);
Dictionary<string, object> saveValues = new Dictionary<string, object>{
{"playerName" , playerName},
{"playerCoin" , playerCoin},
{"playerInventory" , plyaerInventoryItems},
};
DocumentReference docRef = db.Collection("PlayerData").Document(userID);
docRef.SetAsync(saveValues).ContinueWithOnMainThread(task => {
if(task.IsCompleted){
saveStatText.text = "Save Completed Firestore";
}
else{
saveStatText.text = "Failed to save data to firestore";
}
});
}else{
//firebase_Not_Connected_error
Debug.LogError("firebase Not connected to save");
}
}
public void LoadData(){
if(IsConnected){
FirebaseFirestore db = FirebaseFirestore.DefaultInstance;
DocumentReference docRef = db.Collection("PlayerData").Document(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");
coinsTxt.text = snapshot.GetValue<int>("playerCoin").ToString();
List<string> inventoryList = snapshot.GetValue<List<string>>("playerInventory");
item1Txt.text = inventoryList[0];
item2Txt.text = inventoryList[1];
item3Txt.text = inventoryList[2];
}else{
//show error previous data doesnt exists to load
Debug.Log("No previous data to load");
}
});
}
}
public TMP_InputField registerEmail, registerPassword;
public void RegisterUser(){
Firebase.Auth.FirebaseAuth auth = Firebase.Auth.FirebaseAuth.DefaultInstance;
auth.CreateUserWithEmailAndPasswordAsync(registerEmail.text, registerPassword.text).ContinueWith(task => {
if (task.IsCanceled) {
Debug.LogError("CreateUserWithEmailAndPasswordAsync was canceled.");
return;
}
if (task.IsFaulted) {
Debug.LogError("CreateUserWithEmailAndPasswordAsync encountered an error: " + task.Exception);
return;
}
// Firebase user has been created.
Firebase.Auth.AuthResult result = task.Result;
Debug.LogFormat("Firebase user created successfully: {0} ({1})",
result.User.DisplayName, result.User.UserId);
OnAuthSuccess(result.User);
userNameCloud = registerEmail.text;
});
}
public TMP_InputField loginEmail, loginPassword;
public void LoginUser(){
Firebase.Auth.FirebaseAuth auth = Firebase.Auth.FirebaseAuth.DefaultInstance;
auth.SignInWithEmailAndPasswordAsync(loginEmail.text, loginPassword.text).ContinueWith(task => {
if (task.IsCanceled) {
Debug.LogError("SignInWithEmailAndPasswordAsync was canceled.");
return;
}
if (task.IsFaulted) {
Debug.LogError("SignInWithEmailAndPasswordAsync encountered an error: " + task.Exception);
return;
}
Firebase.Auth.AuthResult result = task.Result;
Debug.LogFormat("User signed in successfully: {0} ({1})",
result.User.DisplayName, result.User.UserId);
OnAuthSuccess(result.User);
userNameCloud = loginEmail.text;
});
}
void ConnectToFirebase(){
AuthCode=PlayGamesPlatform.Instance.GetServerAuthCode();
Debug.Log("Gplay auth " + AuthCode);
Firebase.Auth.FirebaseAuth FBAuth = Firebase.Auth.FirebaseAuth.DefaultInstance;
Firebase.Auth.Credential FBCred = Firebase.Auth.PlayGamesAuthProvider.GetCredential(AuthCode);
FBAuth.SignInWithCredentialAsync(FBCred).ContinueWithOnMainThread(task => {
if(task.IsCanceled){
firebaseStatText.text = "sign in cancelled";
}
if(task.IsFaulted){
firebaseStatText.text = "Error:"+task.Result;
}
Firebase.Auth.FirebaseUser user = FBAuth.CurrentUser;
if(user != null){
// userID = user.UserId;
// firebaseStatText.text = "Signed in As :"+ user.DisplayName;
// IsConnected = true;
OnAuthSuccess(user);
userNameCloud = user.DisplayName;
}
else{
//error getting username
}
});
// PlayGamesPlatform.Instance.RequestServerSideAccess(true , code => {
// AuthCode = code;
// Firebase.Auth.FirebaseAuth FBAuth = Firebase.Auth.FirebaseAuth.DefaultInstance;
// Firebase.Auth.Credential FBCred = Firebase.Auth.PlayGamesAuthProvider.GetCredential(AuthCode);
// FBAuth.SignInWithCredentialAsync(FBCred).ContinueWithOnMainThread(task => {
// if(task.IsCanceled){
// firebaseStatText.text = "sign in cancelled";
// }
// if(task.IsFaulted){
// firebaseStatText.text = "Error:"+task.Result;
// }
// Firebase.Auth.FirebaseUser user = FBAuth.CurrentUser;
// if(user != null){
// firebaseStatText.text = "Signed in As :"+ user.DisplayName;
// }
// else{
// //error getting username
// }
// });
// });
}
public void OnAuthSuccess(Firebase.Auth.FirebaseUser user){
userID = user.UserId;
firebaseStatText.text = "Signed in As :"+ user.DisplayName;
IsConnected = true;
//load game scene
SceneManager.LoadScene("MenuScene");
}
#endif
}

View File

@@ -1,11 +1,11 @@
fileFormatVersion: 2
guid: e0a952a0ab83a4cc596b4f665e0a4812
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
fileFormatVersion: 2
guid: e0a952a0ab83a4cc596b4f665e0a4812
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -1,19 +1,19 @@
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class healthBar : MonoBehaviour{
public Slider slider;
public void SetMaxHealth(int health){
slider.maxValue = health;
slider.value = health;
}
public void SetHealth(int health){
slider.value = health;
}
}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class healthBar : MonoBehaviour{
public Slider slider;
public void SetMaxHealth(int health){
slider.maxValue = health;
slider.value = health;
}
public void SetHealth(int health){
slider.value = health;
}
}

View File

@@ -1,11 +1,11 @@
fileFormatVersion: 2
guid: d6a40c4b0b33f484894b4fb85f24438e
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
fileFormatVersion: 2
guid: d6a40c4b0b33f484894b4fb85f24438e
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -1,128 +1,128 @@
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;
public class joystick : MonoBehaviour
{
public bool touchDown;
public bool autoConfigMaxDist;
public float maxDist;
public Vector2 input;
public Vector2 deltaPos;
public Vector2 startPos;
public Vector2 endPos;
public RectTransform joyBG;
public RectTransform joyStick;
public static Vector2 Input => instance.input;
public static joystick instance;
void Awake(){
instance = this;
}
void Update()
{/*
if (autoConfigMaxDist)
{
maxDist = joyBG.sizeDelta.x / 2;
}
if (touchDown)
{
if (Input.touchCount > 0)
{
Touch[] tlist = Input.touches;
int tId = 0;
for (int i = 0; i < tlist.Length; i++)
{
if (tlist[tId].position.x < Screen.width / 2)
{
tId = i;
continue;
}
}
if(tlist[tId].position.x > Screen.width / 2) { return; }
endPos = tlist[tId].position;
}
else if (Input.mousePosition.x < Screen.width / 2)
{
endPos = Input.mousePosition;
}
deltaPos = endPos - startPos;
deltaPos = new Vector2(Mathf.Clamp(deltaPos.x, -maxDist, maxDist), Mathf.Clamp(deltaPos.y, -maxDist, +maxDist));
}
else
{
// deltaPos = Vector2.zero;
}
Vector2 _input = new Vector2(deltaPos.x / maxDist, deltaPos.y / maxDist);
if(_input.magnitude < 0.1f)
{
return;
}
input = _input;
input = (input.magnitude > 1.0f) ? input.normalized : input;
joyStick.localPosition = new Vector2(input.x * (joyBG.sizeDelta.x / 2f), input.y * (joyBG.sizeDelta.y / 2f));
*/
}
public void onDrag(BaseEventData pointer)
{
PointerEventData ped = pointer as PointerEventData;
endPos = ped.position;
deltaPos = endPos - startPos;
deltaPos = new Vector2(Mathf.Clamp(deltaPos.x, -maxDist, maxDist), Mathf.Clamp(deltaPos.y, -maxDist, +maxDist));
Vector2 _input = new Vector2(deltaPos.x / maxDist, deltaPos.y / maxDist);
if (_input.magnitude < 0.1f)
{
return;
}
input = _input;
input = (input.magnitude > 1.0f) ? input.normalized : input;
joyStick.localPosition = new Vector2(input.x * (joyBG.sizeDelta.x / 2f), input.y * (joyBG.sizeDelta.y / 2f));
}
public void pointerDown(BaseEventData pointer)
{
PointerEventData ped = pointer as PointerEventData;
startJoy(ped);
}
public void pointerUp()
{
endJoy();
}
void startJoy(PointerEventData pointer)
{
startPos = pointer.position;
joyBG.gameObject.SetActive(true);
joyStick.gameObject.SetActive(true);
joyStick.localPosition = Vector2.zero;
joyBG.position = startPos;
touchDown = true;
}
void endJoy()
{
// joyBG.gameObject.SetActive(false);
// joyStick.gameObject.SetActive(false);
input = Vector2.zero;
touchDown = false;
joyStick.localPosition = Vector2.zero;
}
}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;
public class joystick : MonoBehaviour
{
public bool touchDown;
public bool autoConfigMaxDist;
public float maxDist;
public Vector2 input;
public Vector2 deltaPos;
public Vector2 startPos;
public Vector2 endPos;
public RectTransform joyBG;
public RectTransform joyStick;
public static Vector2 Input => instance.input;
public static joystick instance;
void Awake(){
instance = this;
}
void Update()
{/*
if (autoConfigMaxDist)
{
maxDist = joyBG.sizeDelta.x / 2;
}
if (touchDown)
{
if (Input.touchCount > 0)
{
Touch[] tlist = Input.touches;
int tId = 0;
for (int i = 0; i < tlist.Length; i++)
{
if (tlist[tId].position.x < Screen.width / 2)
{
tId = i;
continue;
}
}
if(tlist[tId].position.x > Screen.width / 2) { return; }
endPos = tlist[tId].position;
}
else if (Input.mousePosition.x < Screen.width / 2)
{
endPos = Input.mousePosition;
}
deltaPos = endPos - startPos;
deltaPos = new Vector2(Mathf.Clamp(deltaPos.x, -maxDist, maxDist), Mathf.Clamp(deltaPos.y, -maxDist, +maxDist));
}
else
{
// deltaPos = Vector2.zero;
}
Vector2 _input = new Vector2(deltaPos.x / maxDist, deltaPos.y / maxDist);
if(_input.magnitude < 0.1f)
{
return;
}
input = _input;
input = (input.magnitude > 1.0f) ? input.normalized : input;
joyStick.localPosition = new Vector2(input.x * (joyBG.sizeDelta.x / 2f), input.y * (joyBG.sizeDelta.y / 2f));
*/
}
public void onDrag(BaseEventData pointer)
{
PointerEventData ped = pointer as PointerEventData;
endPos = ped.position;
deltaPos = endPos - startPos;
deltaPos = new Vector2(Mathf.Clamp(deltaPos.x, -maxDist, maxDist), Mathf.Clamp(deltaPos.y, -maxDist, +maxDist));
Vector2 _input = new Vector2(deltaPos.x / maxDist, deltaPos.y / maxDist);
if (_input.magnitude < 0.1f)
{
return;
}
input = _input;
input = (input.magnitude > 1.0f) ? input.normalized : input;
joyStick.localPosition = new Vector2(input.x * (joyBG.sizeDelta.x / 2f), input.y * (joyBG.sizeDelta.y / 2f));
}
public void pointerDown(BaseEventData pointer)
{
PointerEventData ped = pointer as PointerEventData;
startJoy(ped);
}
public void pointerUp()
{
endJoy();
}
void startJoy(PointerEventData pointer)
{
startPos = pointer.position;
joyBG.gameObject.SetActive(true);
joyStick.gameObject.SetActive(true);
joyStick.localPosition = Vector2.zero;
joyBG.position = startPos;
touchDown = true;
}
void endJoy()
{
// joyBG.gameObject.SetActive(false);
// joyStick.gameObject.SetActive(false);
input = Vector2.zero;
touchDown = false;
joyStick.localPosition = Vector2.zero;
}
}

View File

@@ -1,11 +1,11 @@
fileFormatVersion: 2
guid: 4c3e2498228fa499982a8458095f71c4
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
fileFormatVersion: 2
guid: 4c3e2498228fa499982a8458095f71c4
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -1,122 +1,122 @@
using System.Collections;
using System.Collections.Generic;
using System.Xml.Serialization;
using TMPro;
using UnityEngine;
using UnityEngine.UI;
public class npcScript : MonoBehaviour
{
public GameObject npcPanel;
public GameObject textBtn;
public TMP_Text npcText;
// public string[] texts;
public QuestScriptable [] questData;
public int activeQuest;
private int index;
//public GameObject questUI;
public float textspeed = 0.10f;
public bool isPlayerClose;
void Update()
{
if(isPlayerClose){
// if(npcPanel.activeInHierarchy){
// ResetTexts();
// }else{
// npcPanel.SetActive(true);
// StartCoroutine(textLoad());
// }
}
if(npcText.text == questData[activeQuest].questLines[index]){
textBtn.SetActive(true);
}
}
public void ResetTexts(){
npcPanel.SetActive(false);
npcText.text = "";
index = 0;
}
bool isLooping = false;
IEnumerator textLoad(){
isLooping = true;
foreach(char letter in questData[activeQuest].questLines[index].ToCharArray()){
npcText.text += letter;
yield return new WaitForSecondsRealtime(textspeed);
}
isLooping=false;
}
Coroutine textLoopAsync ;
public void NextLine(){
textBtn.SetActive(false);
if(index < questData[activeQuest].questLines.Length -1 ){
index++;
npcText.text = "";
LoadText();
}else{
ResetTexts();
//Start quest
// questUI.SetActive(true);
playerNetwork.localPlayerTransform.GetComponent<playerNetwork>().QuestFunction(questData[activeQuest]);
}
}
private void OnTriggerEnter2D(Collider2D other) {
if(other.CompareTag("Player")){
if(other.transform == playerNetwork.localPlayerTransform){
if(playerNetwork.localPlayerTransform.GetComponent<playerNetwork>().currentQuest == questData[activeQuest]){
return;
}
for(int i =0; i < questData.Length; i++){
bool isFound = false;
foreach(string questName in playerNetwork.localPlayerTransform.GetComponent<playerNetwork>().completedQuests){
if(questName == questData[i].name){
isFound = true;
}
}
if(!isFound){
activeQuest = i;
break;
}
}
isPlayerClose = true;
if(npcPanel.activeInHierarchy){
ResetTexts();
}else{
npcPanel.SetActive(true);
LoadText();
}
}
}
}
void LoadText(){
npcText.text = "";
if(textLoopAsync!=null){
StopCoroutine(textLoopAsync);
}
textLoopAsync = StartCoroutine(textLoad());
}
private void OnTriggerExit2D(Collider2D other) {
if(other.CompareTag("Player")){
if(other.transform == playerNetwork.localPlayerTransform){
isPlayerClose = false;
ResetTexts();
}
}
}
}
using System.Collections;
using System.Collections.Generic;
using System.Xml.Serialization;
using TMPro;
using UnityEngine;
using UnityEngine.UI;
public class npcScript : MonoBehaviour
{
public GameObject npcPanel;
public GameObject textBtn;
public TMP_Text npcText;
// public string[] texts;
public QuestScriptable [] questData;
public int activeQuest;
private int index;
//public GameObject questUI;
public float textspeed = 0.10f;
public bool isPlayerClose;
void Update()
{
if(isPlayerClose){
// if(npcPanel.activeInHierarchy){
// ResetTexts();
// }else{
// npcPanel.SetActive(true);
// StartCoroutine(textLoad());
// }
}
if(npcText.text == questData[activeQuest].questLines[index]){
textBtn.SetActive(true);
}
}
public void ResetTexts(){
npcPanel.SetActive(false);
npcText.text = "";
index = 0;
}
bool isLooping = false;
IEnumerator textLoad(){
isLooping = true;
foreach(char letter in questData[activeQuest].questLines[index].ToCharArray()){
npcText.text += letter;
yield return new WaitForSecondsRealtime(textspeed);
}
isLooping=false;
}
Coroutine textLoopAsync ;
public void NextLine(){
textBtn.SetActive(false);
if(index < questData[activeQuest].questLines.Length -1 ){
index++;
npcText.text = "";
LoadText();
}else{
ResetTexts();
//Start quest
// questUI.SetActive(true);
playerNetwork.localPlayerTransform.GetComponent<playerNetwork>().QuestFunction(questData[activeQuest]);
}
}
private void OnTriggerEnter2D(Collider2D other) {
if(other.CompareTag("Player")){
if(other.transform == playerNetwork.localPlayerTransform){
if(playerNetwork.localPlayerTransform.GetComponent<playerNetwork>().currentQuest == questData[activeQuest]){
return;
}
for(int i =0; i < questData.Length; i++){
bool isFound = false;
foreach(string questName in playerNetwork.localPlayerTransform.GetComponent<playerNetwork>().completedQuests){
if(questName == questData[i].name){
isFound = true;
}
}
if(!isFound){
activeQuest = i;
break;
}
}
isPlayerClose = true;
if(npcPanel.activeInHierarchy){
ResetTexts();
}else{
npcPanel.SetActive(true);
LoadText();
}
}
}
}
void LoadText(){
npcText.text = "";
if(textLoopAsync!=null){
StopCoroutine(textLoopAsync);
}
textLoopAsync = StartCoroutine(textLoad());
}
private void OnTriggerExit2D(Collider2D other) {
if(other.CompareTag("Player")){
if(other.transform == playerNetwork.localPlayerTransform){
isPlayerClose = false;
ResetTexts();
}
}
}
}

View File

@@ -1,11 +1,11 @@
fileFormatVersion: 2
guid: e46c9f63c22284bc78d900f8086d1d89
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
fileFormatVersion: 2
guid: e46c9f63c22284bc78d900f8086d1d89
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -1,65 +1,65 @@
using System.Collections;
using System.Collections.Generic;
using Mirror;
using UnityEngine;
public class pickup : NetworkBehaviour
{
public string lootType = "default";
public item lootData;
float updaterInterval = 0.4f;
void Awake(){
updaterInterval += Random.Range(0,0.2f);
}
float t = 0;
public float pickupDistance = 2;
public float closestPlayerDist = float.MaxValue;
[Server]
void Update(){
if(t < updaterInterval){
t += Time.deltaTime;
}else{
ScanPlayers();
t=0;
}
}
void ScanPlayers(){
playerNetwork[] players = FindObjectsOfType<playerNetwork>();
if(players.Length <=0){return;}
playerNetwork closestPlayer = players[0];
closestPlayerDist = float.MaxValue;
foreach(playerNetwork player in players){
float dist = Vector3.Distance(transform.position, player.transform.position);
if(dist < closestPlayerDist){
closestPlayer = player;
closestPlayerDist= dist;
}
}
if(closestPlayerDist < pickupDistance){
closestPlayer.PickupObject(this);
NetworkServer.Destroy(gameObject);
}
}
// private void OnTriggerEnter2D(Collider2D other) {
// if(other.CompareTag("Player")){
// for(int i = 0; i < inventory.slots.Length ; i++){
// if(inventory.isFull[i] == false){
// //then the item can be addded to the inventory
// inventory.isFull[i] = true;
// //instantiate the pickup item
// Instantiate(itemBtn , inventory.slots[i].transform , false);
// Destroy(gameObject);
// break;
// }
// }
// }
// }
}
using System.Collections;
using System.Collections.Generic;
using Mirror;
using UnityEngine;
public class pickup : NetworkBehaviour
{
public string lootType = "default";
public item lootData;
float updaterInterval = 0.4f;
void Awake(){
updaterInterval += Random.Range(0,0.2f);
}
float t = 0;
public float pickupDistance = 2;
public float closestPlayerDist = float.MaxValue;
[Server]
void Update(){
if(t < updaterInterval){
t += Time.deltaTime;
}else{
ScanPlayers();
t=0;
}
}
void ScanPlayers(){
playerNetwork[] players = FindObjectsOfType<playerNetwork>();
if(players.Length <=0){return;}
playerNetwork closestPlayer = players[0];
closestPlayerDist = float.MaxValue;
foreach(playerNetwork player in players){
float dist = Vector3.Distance(transform.position, player.transform.position);
if(dist < closestPlayerDist){
closestPlayer = player;
closestPlayerDist= dist;
}
}
if(closestPlayerDist < pickupDistance){
closestPlayer.PickupObject(this);
NetworkServer.Destroy(gameObject);
}
}
// private void OnTriggerEnter2D(Collider2D other) {
// if(other.CompareTag("Player")){
// for(int i = 0; i < inventory.slots.Length ; i++){
// if(inventory.isFull[i] == false){
// //then the item can be addded to the inventory
// inventory.isFull[i] = true;
// //instantiate the pickup item
// Instantiate(itemBtn , inventory.slots[i].transform , false);
// Destroy(gameObject);
// break;
// }
// }
// }
// }
}

View File

@@ -1,11 +1,11 @@
fileFormatVersion: 2
guid: f6813cd00ed9b461196d0892f7a115f4
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
fileFormatVersion: 2
guid: f6813cd00ed9b461196d0892f7a115f4
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -1,79 +1,79 @@
using System.Collections;
using System.Collections.Generic;
using Mirror;
using UnityEngine;
using TMPro;
using System;
public class playerChat : NetworkBehaviour
{
[SerializeField] private GameObject chatUI = null;
[SerializeField] private TMP_Text chatText = null;
[SerializeField] private TMP_InputField inputField = null;
private static event Action<string> OnMessage;
public override void OnStartAuthority()
{
base.OnStartAuthority();
Debug.Log("Chat has authorized");
chatUI.SetActive(true);
OnMessage += HandleNewMessage;
}
[ClientCallback]
private void OnDestroy()
{
if (!authority) { return; }
OnMessage -= HandleNewMessage;
}
private void HandleNewMessage(string message)
{
chatText.text += message;
}
[Client]
public void Send(string message)
{
if (!Input.GetKeyDown(KeyCode.Return)) { return; }
if (string.IsNullOrWhiteSpace(message)) { return; }
CmdSendMessage(message);
inputField.text = string.Empty;
}
[Client]
public void SendBtn(){
if (string.IsNullOrWhiteSpace(inputField.text)) { return; }
CmdSendMessage($"{gplayAuth.userNameCloud}: "+inputField.text);
inputField.text = string.Empty;
}
[Command]
private void CmdSendMessage(string message)
{
// RpcHandleMessage($"[{gplayAuth.userNameCloud}]: {message}");
RpcHandleMessage(message);
}
[ClientRpc]
private void RpcHandleMessage(string message)
{
OnMessage?.Invoke($"\n{message}");
}
}
using System.Collections;
using System.Collections.Generic;
using Mirror;
using UnityEngine;
using TMPro;
using System;
public class playerChat : NetworkBehaviour
{
[SerializeField] private GameObject chatUI = null;
[SerializeField] private TMP_Text chatText = null;
[SerializeField] private TMP_InputField inputField = null;
private static event Action<string> OnMessage;
public override void OnStartAuthority()
{
base.OnStartAuthority();
Debug.Log("Chat has authorized");
chatUI.SetActive(true);
OnMessage += HandleNewMessage;
}
[ClientCallback]
private void OnDestroy()
{
if (!authority) { return; }
OnMessage -= HandleNewMessage;
}
private void HandleNewMessage(string message)
{
chatText.text += message;
}
[Client]
public void Send(string message)
{
if (!Input.GetKeyDown(KeyCode.Return)) { return; }
if (string.IsNullOrWhiteSpace(message)) { return; }
CmdSendMessage(message);
inputField.text = string.Empty;
}
[Client]
public void SendBtn(){
if (string.IsNullOrWhiteSpace(inputField.text)) { return; }
CmdSendMessage($"{gplayAuth.userNameCloud}: "+inputField.text);
inputField.text = string.Empty;
}
[Command]
private void CmdSendMessage(string message)
{
// RpcHandleMessage($"[{gplayAuth.userNameCloud}]: {message}");
RpcHandleMessage(message);
}
[ClientRpc]
private void RpcHandleMessage(string message)
{
OnMessage?.Invoke($"\n{message}");
}
}

View File

@@ -1,11 +1,11 @@
fileFormatVersion: 2
guid: 22f98272f46e846febf258ff48778164
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
fileFormatVersion: 2
guid: 22f98272f46e846febf258ff48778164
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

File diff suppressed because it is too large Load Diff

View File

@@ -1,11 +1,11 @@
fileFormatVersion: 2
guid: a0e742454c50a43738d8e87c32a3c168
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
fileFormatVersion: 2
guid: a0e742454c50a43738d8e87c32a3c168
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -1,33 +1,33 @@
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class roomChecker : MonoBehaviour
{
public GameObject outerGrid;
public GameObject caveGrid;
private void OnTriggerEnter2D(Collider2D other) {
if(other.tag == "Player"){
if(other.transform == playerNetwork.localPlayerTransform){
outerGrid.SetActive(false);
caveGrid.SetActive(true);
}
}
}
private void OnTriggerExit2D(Collider2D other) {
if(other.tag == "Player"){
if(other.transform == playerNetwork.localPlayerTransform){
outerGrid.SetActive(true);
caveGrid.SetActive(false);
}
}
}
void Update()
{
}
}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class roomChecker : MonoBehaviour
{
public GameObject outerGrid;
public GameObject caveGrid;
private void OnTriggerEnter2D(Collider2D other) {
if(other.tag == "Player"){
if(other.transform == playerNetwork.localPlayerTransform){
outerGrid.SetActive(false);
caveGrid.SetActive(true);
}
}
}
private void OnTriggerExit2D(Collider2D other) {
if(other.tag == "Player"){
if(other.transform == playerNetwork.localPlayerTransform){
outerGrid.SetActive(true);
caveGrid.SetActive(false);
}
}
}
void Update()
{
}
}

View File

@@ -1,11 +1,11 @@
fileFormatVersion: 2
guid: cd3fad1babd0a4437a6f2a27d8cf35c5
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
fileFormatVersion: 2
guid: cd3fad1babd0a4437a6f2a27d8cf35c5
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -1,23 +1,23 @@
using System.Collections;
using System.Collections.Generic;
using Mirror;
using UnityEngine;
public class startClient : MonoBehaviour
{
public NetworkManager networkManager;
public static startClient instance;
void Awake(){
instance = this;
}
void Start()
{
networkManager.StartClient();
}
// Update is called once per frame
void Update()
{
}
}
using System.Collections;
using System.Collections.Generic;
using Mirror;
using UnityEngine;
public class startClient : MonoBehaviour
{
public NetworkManager networkManager;
public static startClient instance;
void Awake(){
instance = this;
}
void Start()
{
networkManager.StartClient();
}
// Update is called once per frame
void Update()
{
}
}

View File

@@ -1,11 +1,11 @@
fileFormatVersion: 2
guid: d3a46f3965e4c4fca9282d03e7c4ecf9
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
fileFormatVersion: 2
guid: d3a46f3965e4c4fca9282d03e7c4ecf9
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -1,18 +1,18 @@
using System.Collections;
using System.Collections.Generic;
using JetBrains.Annotations;
using UnityEngine;
public class teleporter : MonoBehaviour
{
public Transform teleportLocation;
private void OnTriggerEnter2D(Collider2D other) {
if(other.tag == "Player"){
if(other.transform == playerNetwork.localPlayerTransform){
other.transform.position = teleportLocation.position;
cameraRPG.instance.Teleport(teleportLocation.position);
}
}
}
}
using System.Collections;
using System.Collections.Generic;
using JetBrains.Annotations;
using UnityEngine;
public class teleporter : MonoBehaviour
{
public Transform teleportLocation;
private void OnTriggerEnter2D(Collider2D other) {
if(other.tag == "Player"){
if(other.transform == playerNetwork.localPlayerTransform){
other.transform.position = teleportLocation.position;
cameraRPG.instance.Teleport(teleportLocation.position);
}
}
}
}

View File

@@ -1,11 +1,11 @@
fileFormatVersion: 2
guid: ef8a6a639ff9340d6bc0ecfded4481e4
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
fileFormatVersion: 2
guid: ef8a6a639ff9340d6bc0ecfded4481e4
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -1,23 +1,23 @@
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class vfxScript : MonoBehaviour
{
public float destroyTimer = 5f;
// public Transform target;
// public Vector3 offsetVFX;
void Update()
{
//transform.position = target.position + offsetVFX;
destroyTimer -= Time.deltaTime;
if(destroyTimer < 0){
Destroy(gameObject);
}
}
}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class vfxScript : MonoBehaviour
{
public float destroyTimer = 5f;
// public Transform target;
// public Vector3 offsetVFX;
void Update()
{
//transform.position = target.position + offsetVFX;
destroyTimer -= Time.deltaTime;
if(destroyTimer < 0){
Destroy(gameObject);
}
}
}

View File

@@ -1,11 +1,11 @@
fileFormatVersion: 2
guid: 455bda62d3da14373abacdeeff41ad61
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
fileFormatVersion: 2
guid: 455bda62d3da14373abacdeeff41ad61
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant: