Last active
July 9, 2018 05:18
-
-
Save chitimalli/dac1c828d5f4ede2078ea879130625c2 to your computer and use it in GitHub Desktop.
This is one of the core classes in SmashWars that controls player movement in the game.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using UnityEngine; | |
using System.Collections; | |
using System.Linq; | |
using System.Collections.Generic; | |
using CodeStage.AntiCheat.ObscuredTypes; | |
public class DBMgr : MonoBehaviour | |
{ | |
public static DBMgr Instance; | |
public delegate void CurrencuyUpdated(); | |
public static event CurrencuyUpdated CurrencyUpdateEvent; | |
public enum DIFFICULTY | |
{ | |
ROOKIE = 0, | |
AMATEUR = 1, | |
PROFESSIONAL = 2, | |
SUPERSTAR = 3, | |
INVALID = 4 // Use this for Code, keep moving this down, add a new boost above it | |
} | |
public enum GAME_MODE | |
{ | |
LOCAL = 0, | |
CARDBOARD = 1, | |
WITH_FRIENDS = 2, | |
BATTLES = 3, | |
TOURNAMENTS = 4, | |
INVALID // Use this for Code, keep moving this down, add a new boost above it | |
} | |
public enum PanelType | |
{ | |
HomePanel = 0, | |
DronePanel, | |
LevelPanel | |
} | |
public enum CURRENCY | |
{ | |
COIN, //Coins INGAME | |
GEM, //Gems //Premium | |
TROPHY, //Gems //Premium | |
HEART, //Gems //Premium | |
} | |
public enum Toggle_Type | |
{ | |
MUSIC, | |
SFX, | |
FPV, | |
GVR, | |
TILT | |
} | |
public enum ShipFeature | |
{ | |
SMASH = 0, | |
HANDLING = 1, | |
THRUST = 2 | |
} | |
public enum BOOST_TYPE | |
{ | |
WORD_RAND = 0, // Allows Random word pick | |
WORD_CLEAR = 1, //Clears found alphabest | |
WORD_HINT = 2, //Hints the word to be found | |
AUTO_FUEL = 3, // Enable refueling | |
AUTO_SHIELD = 4, // Repairs shields on Smash | |
MORE_COIN = 5, // Gives Coin on Smash | |
// Any new boost goes here | |
MAX_BOOST // Use this for Code, keep moving this down, add a new boost above it | |
} | |
public enum WATCH_AD_REWARD | |
{ | |
REWARD_GEM = 0, | |
MULLIGAN_PLAY = 1, | |
EARN_GEM = 2, | |
EARN_COIN = 3, | |
TRY_SHIP = 4, | |
DOUBLE_GOLD = 5 | |
} | |
public enum CAMERA_TYPE | |
{ | |
GEAR_VR = 0, | |
CARDBOARD = 1, | |
SCREEN_2D = 2, | |
TV = 3, | |
MAX_PLATFROM | |
} | |
public enum LB_TABPANEL | |
{ | |
WORLD = 0, | |
FRIENDS = 1, | |
MAX_PLATFROM | |
} | |
public enum IAP_TYPE | |
{ | |
GEM_SMALL = 0, | |
GEM_MED = 1, | |
GEM_LARGE = 2, | |
GEM_XLARGE = 3, | |
GEM_XXLARGE = 4, | |
GEM_XXXLARGE = 5, | |
COIN_SMALL = 0, | |
COIN_MED = 1, | |
COIN_LARGE = 2, | |
COIN_XLARGE = 3, | |
COIN_XXLARGE = 4, | |
Coin_XXXLARGE = 5, | |
} | |
//Gameconstants | |
public static float[] _mulliganConstant; | |
public static float _mulliganAutoCloseDelay;// = 2.0f; | |
public static float _mulliganShowAfterDelay;// = 1.0f; | |
public static float _mulliganRespawnDelay;// = 2.0f; | |
public static int _mulliganMaxPerGame;// = 1; | |
public static int _mulliganCost;// = 10; | |
public static int _gemsPerAdView;// = 10; | |
public static int _coinToGemConversion; // = 5; | |
public static int _cameraFOV; // = 1.0f; | |
public static string _gameCreditsText; | |
public static string _copyRightText; | |
public static string _termsOfServiceURL; | |
public static float[] _cameraZoomLevels; | |
public static int[] _boostCostInCoins; | |
public static int[] _boostUnlockLevel; | |
public static string[] _boostNames; | |
public static string[] _boostInfo; | |
public static string[] _smashyTips; | |
public static int[] _gameDiffMinTrophy; | |
public static int[] _gameDiffEntryCost; | |
public static int[] _gameRewardPerWord; | |
public static int coinPerAdView; | |
public static int gemPerAdView; | |
public static string _facebookAppID; | |
public static string _iTunesConnectURL; | |
public static string _gamePostImageURL; | |
public static string _gameName; | |
public static string _gameCaption; | |
public static string _tweetAddress; | |
public static string _facebookPageURL; | |
public static string _previewImageURL; | |
public static string _facebookAppLinkURL; | |
public static string _getCardboardURL; | |
public static bool[] toggleSettings;// = true; | |
public static bool zoomEnabled;// = 1; | |
public static bool musicEnabled;// = true; | |
public static bool sfxEnabled;// = true; | |
public static bool tiltEnabled;// = true; | |
//Player Progress | |
public static string lastPlayedShipID;// = "ship_0"; | |
public static string lastPilotID;// = "ship_0"; | |
public string[] ownedShips; | |
public string[] unlockedShips; | |
//public int shipColorID;// = new Dictionary<string,string>(); | |
public int[] shipHandlingLevels; | |
public int[] shipThrustLevels;// = new Dictionary<string,string>(); | |
public int[] shipSpeedLevels;// = new Dictionary<string,string>(); | |
//Stats per Ship | |
public int[] shipTotalCrashes;// = new Dictionary<string,string>(); | |
public int[] shipTotalSmashes;// = new Dictionary<string,string>(); | |
public int[] shipTotalDistance;// = new Dictionary<string,string>(); | |
public int[] shipRecordDistance;// = new Dictionary<string,string>(); | |
public int[] shipRecordSmashes;// = new Dictionary<string,string>(); | |
public static ObscuredBool hasNoAdsPack = false; | |
public static ObscuredBool hasCoinDoublerPack = false; | |
public static ObscuredBool hasStarterPack = false; | |
//GamePlay | |
public static ObscuredBool _showDistanceStat = false; | |
public static ObscuredInt _minTrophyForFTUESKIP = 5; | |
//#endregion | |
void Awake() | |
{ | |
DontDestroyOnLoad(transform.root.gameObject); | |
Instance = this; | |
if (PlayerPrefs.HasKey("PlayerClientVersion")) | |
{ | |
//Sounds like the client has a very old version of client, lets clear it.. | |
PlayerPrefs.DeleteAll(); | |
} | |
InitAndLoadLocalTitleData(); | |
InitAndLoadPlayerData(); | |
} | |
void Start() | |
{ | |
//PlayerPrefs.DeleteAll(); | |
//Double check if player meet the criteria for cardboard | |
//CBModeEnabled = CBModeEnabled ? (PlayerLevel >= _gameModeUnlockAt[(int)GAME_MODE.CARDBOARD]) : false; | |
//GameCamera.Instance.UpdateCardBoard(); | |
} | |
public void ResetLocalData() | |
{ | |
PlayerPrefs.DeleteAll(); | |
ObscuredPrefs.DeleteAll(); | |
} | |
public static string debugInfo = ""; | |
public static int numLines = 0; | |
public static void Log(string text) | |
{ | |
Debug.Log(text); | |
numLines += 1; | |
if (numLines > 150) | |
{ | |
debugInfo = ""; | |
numLines = 0; | |
} | |
debugInfo += "Ln:" + numLines + ": " + text + "\n"; | |
} | |
public static int TotalGems | |
{ | |
get { return PlayerPrefsX.GetInt(Constants.VC_TotalGems, 10); } | |
set | |
{ | |
PlayerPrefsX.SetInt(Constants.VC_TotalGems, Mathf.Clamp(value, 0, value)); | |
if (CurrencyUpdateEvent != null) | |
CurrencyUpdateEvent(); | |
} | |
} | |
public static int TotalCoins | |
{ | |
get { return PlayerPrefsX.GetInt(Constants.VC_TotalCoins, 1000); } | |
set | |
{ | |
PlayerPrefsX.SetInt(Constants.VC_TotalCoins, Mathf.Clamp(value, 0, value)); | |
if (CurrencyUpdateEvent != null) | |
CurrencyUpdateEvent(); | |
} | |
} | |
public static int TotalTrophy | |
{ | |
get { return PlayerPrefsX.GetInt(Constants.VC_TotalTrophy, 0); } | |
set | |
{ | |
PlayerPrefsX.SetInt(Constants.VC_TotalTrophy, Mathf.Clamp(value, 0, value)); | |
if (CurrencyUpdateEvent != null) | |
CurrencyUpdateEvent(); | |
} | |
} | |
public static int GetCurrency(CURRENCY curr) | |
{ | |
if (curr == CURRENCY.COIN) | |
return TotalCoins; | |
if (curr == CURRENCY.GEM) | |
return TotalGems; | |
if (curr == CURRENCY.TROPHY) | |
return TotalTrophy; | |
return 0; | |
} | |
public static void SetCurrency(CURRENCY curr, int newVal) | |
{ | |
//Debug.Log(">>>> Setting currency : "+GetCurrencyKey(curr) +" to :"+newVal); | |
if (curr == CURRENCY.COIN) | |
TotalCoins = newVal; | |
if (curr == CURRENCY.GEM) | |
TotalGems = newVal; | |
if (curr == CURRENCY.TROPHY) | |
TotalTrophy = newVal; | |
} | |
public static string GetCurrencyKey(CURRENCY curr) | |
{ | |
if (curr == CURRENCY.COIN) | |
return Constants.COIN_KEY; | |
if (curr == CURRENCY.GEM) | |
return Constants.GEM_KEY; | |
if (curr == CURRENCY.TROPHY) | |
return Constants.TROPHY_KEY; | |
return null; | |
} | |
public static int PlayerLevel | |
{ | |
get { return PlayerPrefsX.GetInt(Constants.PD_PlayerLevel, 0); } | |
set { PlayerPrefsX.SetInt(Constants.PD_PlayerLevel, Mathf.Clamp(value, 0, value)); } | |
} | |
public static int RecordScore | |
{ | |
get { return PlayerPrefsX.GetInt(Constants.RecordSmashScoreLB, 0); } | |
set { PlayerPrefsX.SetInt(Constants.RecordSmashScoreLB, Mathf.Clamp(value, 0, value)); } | |
} | |
public static int RecordDistance | |
{ | |
get { return PlayerPrefsX.GetInt(Constants.RecordDistanceLB, 0); } | |
set { PlayerPrefsX.SetInt(Constants.RecordDistanceLB, Mathf.Clamp(value, 0, value)); } | |
} | |
//Total | |
public static int TotalSmashes | |
{ | |
get { return PlayerPrefsX.GetInt(Constants.TotalSmashes, 0); } | |
set { PlayerPrefsX.SetInt(Constants.TotalSmashes, Mathf.Clamp(value, 0, value)); } | |
} | |
public static int TotalDistance | |
{ | |
get { return PlayerPrefsX.GetInt(Constants.TotalDistance, 0); } | |
set { PlayerPrefsX.SetInt(Constants.TotalDistance, Mathf.Clamp(value, 0, value)); } | |
} | |
public static int TotalCrashes | |
{ | |
get { return PlayerPrefsX.GetInt(Constants.TotalCrashes, 0); } | |
set { PlayerPrefsX.SetInt(Constants.TotalCrashes, Mathf.Clamp(value, 0, value)); } | |
} | |
public static int TotalWords | |
{ | |
get { return PlayerPrefsX.GetInt(Constants.TotalWords, 0); } | |
set { PlayerPrefsX.SetInt(Constants.TotalWords, Mathf.Clamp(value, 0, value)); } | |
} | |
// Top | |
public static int TopSmashed | |
{ | |
get { return PlayerPrefsX.GetInt(Constants.TopSmashed, 0); } | |
set { PlayerPrefsX.SetInt(Constants.TopSmashed, Mathf.Clamp(value, 0, value)); } | |
} | |
public static int TopScore | |
{ | |
get { return PlayerPrefsX.GetInt(Constants.HighScore, 0); } | |
set { PlayerPrefsX.SetInt(Constants.HighScore, Mathf.Clamp(value, 0, value)); } | |
} | |
public static int TopSurfed | |
{ | |
get { return PlayerPrefsX.GetInt(Constants.TopSurfed, 0); } | |
set { PlayerPrefsX.SetInt(Constants.TopSurfed, Mathf.Clamp(value, 0, value)); } | |
} | |
public static int TopWords | |
{ | |
get { return PlayerPrefsX.GetInt(Constants.TopWords, 0); } | |
set { PlayerPrefsX.SetInt(Constants.TopWords, Mathf.Clamp(value, 0, value)); } | |
} | |
public void InitAndLoadLocalTitleData() | |
{ | |
//GameConstants | |
_mulliganConstant = PlayerPrefsX.GetFloatArray(Constants.TD_mulliganConstants, new float[] { 5.0f, 1.0f, 2.0f, 1.0f, 1.0f, 2500 }); | |
_mulliganAutoCloseDelay = _mulliganConstant[0]; | |
_mulliganShowAfterDelay = _mulliganConstant[1]; | |
_mulliganRespawnDelay = _mulliganConstant[2]; | |
_mulliganMaxPerGame = Mathf.RoundToInt(_mulliganConstant[3]); | |
_mulliganCost = Mathf.RoundToInt(_mulliganConstant[4]); | |
//Economy | |
_coinToGemConversion = PlayerPrefsX.GetInt(Constants.TD_gemToCoinConversion, 100); | |
_gemsPerAdView = PlayerPrefsX.GetInt(Constants.TD_gemsPerAdView, 1); | |
_cameraFOV = PlayerPrefsX.GetInt(Constants.TD_cameraFOV, 75); | |
_cameraZoomLevels = new float[] { 3.5f, 0.75f }; | |
_boostCostInCoins = PlayerPrefsX.GetIntArray(Constants.TD_boostCostInCoins, new int[] { 0, 100, 100, 100, 100, 100, 150, 200, 100 });//50,25; | |
_boostUnlockLevel = PlayerPrefsX.GetIntArray(Constants.TD_boostUnlockLevel, new int[] { 0, 1, 2, 3, 5, 6, 7, 5, 5 });//50,25; //Any Order,Clear Found,Word Hint, Recharge,Repair Shield,More Coin,,, | |
_boostNames = PlayerPrefsX.GetStringArray(Constants.TD_boostNames, new string[] { "Any\nOrder", "Clear\nFound", "Word\nHint", "Fast Recharge", "Fast Repair", "Smash Coins" }); | |
_boostInfo = PlayerPrefsX.GetStringArray(Constants.TD_boostInfo, new string[] { "Pick letters in any order", "Remove found letters", "Word hints shown", "2x recharge on low", "2x shield repair on smash", "Earn Coin on smash" }); | |
_gameDiffMinTrophy = PlayerPrefsX.GetIntArray(Constants.TD_gameDiffMinTrophy, new int[] { 0, 25, 50, 75 }); | |
_gameDiffEntryCost = PlayerPrefsX.GetIntArray(Constants.TD_gameDiffEntryCost, new int[] { 0, 150, 250, 300 }); | |
_gameRewardPerWord = PlayerPrefsX.GetIntArray(Constants.TD_gameDiffRewardPerWord, new int[] { 150, 300, 450, 600 }); | |
_showDistanceStat = PlayerPrefsX.GetInt(Constants.TD_ShowDistStat, 1) == 1 ? true : false; | |
_minTrophyForFTUESKIP = PlayerPrefsX.GetInt(Constants.TD_MinTrophyForFTUESkip, 5); | |
//Social & Sharing features | |
_facebookAppID = PlayerPrefsX.GetString(Constants.TD_facebookAppID, "1673007209622985"); | |
_facebookPageURL = PlayerPrefsX.GetString(Constants.TD_facebookPageURL, "https://www.facebook.com/smashwarsgame/?ref=game_results_like"); | |
_facebookAppLinkURL = PlayerPrefsX.GetString(Constants.TD_facebookAppLinkURL, "https://fb.me/878824722207086"); | |
_previewImageURL = PlayerPrefsX.GetString(Constants.TD_previewImageURL, "https://www.facebook.com/smashwarsgame/?ref=game_results_like"); | |
_iTunesConnectURL = PlayerPrefsX.GetString(Constants.TD_iTunesConnectURL, "https://itunesconnect.apple.com/WebObjects/iTunesConnect.woa/ra/ng/app/1041729945"); | |
_gameName = PlayerPrefsX.GetString(Constants.TD_gameName, "Smash Wars"); | |
_gameCaption = PlayerPrefsX.GetString(Constants.TD_gameCaption, "Smash Till You Crash!"); | |
_tweetAddress = PlayerPrefsX.GetString(Constants.TD_tweetAddress, "http://twitter.com/intent/tweet"); | |
_gameCreditsText = PlayerPrefsX.GetString(Constants.TD_gameCreditsText, ">> Development/Design <<\nAmar Chitimalli\n\n\n>> Art <<\nUnity AssetStore\n\n\n>> Sound <<\nAvaren - SoundCloud (Free)\n\n\n>>Tools<<\nUnity3D, Photoshop, CloudOnce, LeanPlum, GameAnalytics\n\n>>Testing<<\nThanks to all my Beta testers"); | |
_copyRightText = PlayerPrefsX.GetString(Constants.TD_copyRightText, "2016 Copyright - FaunaFace, Inc"); | |
_termsOfServiceURL = PlayerPrefsX.GetString(Constants.TD_termsOfService, "http://faunaface.com/privacy.html"); | |
_getCardboardURL = PlayerPrefsX.GetString(Constants.TD_getCardboardURL, "https://play.google.com/store/apps/details?id=com.faunaface.smashwars.cardboard"); | |
coinPerAdView = DBMgr._gemsPerAdView * DBMgr._coinToGemConversion; | |
gemPerAdView = DBMgr._gemsPerAdView; | |
PlayerPrefs.Save(); | |
} | |
//Managed by cloudOnce | |
public void InitAndLoadPlayerData() | |
{ | |
int numShips = 20; | |
//Player Settings | |
zoomEnabled = PlayerPrefsX.GetBool(Constants.D_FPVEnabled, false); | |
musicEnabled = PlayerPrefsX.GetBool(Constants.D_MusicEnabled, true); | |
sfxEnabled = PlayerPrefsX.GetBool(Constants.D_SoundEnabled, true); | |
tiltEnabled = PlayerPrefsX.GetBool(Constants.D_TiltEnabled, false); | |
//PlayerData | |
//Game Progress | |
lastPlayedShipID = PlayerPrefsX.GetString(Constants.PD_LastPlayedShipID, "drone_0"); | |
ownedShips = PlayerPrefsX.GetStringArray(Constants.PD_PlayerShipInventory, new string[] { "drone_0" }); | |
unlockedShips = PlayerPrefsX.GetStringArray(Constants.PD_PlayerShipsUnlocked, new string[] { "drone_0" }); | |
//Ship Upgrades | |
shipHandlingLevels = PlayerPrefsX.GetIntArray(Constants.PD_ShipHandlingLevels, new int[numShips]); | |
shipThrustLevels = PlayerPrefsX.GetIntArray(Constants.PD_ShipThrustLevels, new int[numShips]); | |
shipSpeedLevels = PlayerPrefsX.GetIntArray(Constants.PD_ShipSmashLevels, new int[numShips]); | |
LoadPermanantIAP(); | |
} | |
public int OwnedItemCount(string shipID) | |
{ | |
return PFMgr.Instance.InventoryItemCount(shipID); | |
} | |
public int UnlockedItemCount(string shipID) | |
{ | |
return (unlockedShips != null && unlockedShips.Contains(shipID)) ? 1 : 0; | |
} | |
public void RewardGemsForAdView() | |
{ | |
PFMgr.Instance.UpdateVC(DBMgr.CURRENCY.GEM, DBMgr.gemPerAdView, Constants.FUN_AdWatched, "Ad Watched for Gems"); | |
} | |
public void RewardCoinsForAdView() | |
{ | |
PFMgr.Instance.UpdateVC(DBMgr.CURRENCY.COIN, DBMgr.coinPerAdView, Constants.FUN_AdWatched, "Ad Watched for Coins"); | |
} | |
public float PlayerZoomLevel | |
{ | |
get { return !zoomEnabled ? _cameraZoomLevels[0] : _cameraZoomLevels[1]; } | |
} | |
public void UpdateVCS(CURRENCY curr, int deltaAmount, string reason) | |
{ | |
if (deltaAmount == 0) | |
return; | |
int newTotal = GetCurrency(curr) + deltaAmount; | |
if (newTotal < 0) | |
{ | |
//We cannot have negative balances, there is an issue in the code, makesure youFix it | |
Debug.LogError("We cannot have negative balances: " + curr + " Amt: " + deltaAmount + " Total: " + newTotal); | |
return; | |
} | |
else | |
{ | |
if (deltaAmount > 0) | |
PFMgr.Instance.UpdateVC(curr, Mathf.Abs(deltaAmount), Constants.FUN_AddVC, reason); | |
else | |
PFMgr.Instance.UpdateVC(curr, Mathf.Abs(deltaAmount), Constants.FUN_SubVC, reason); | |
} | |
} | |
Dictionary<string, string> UpdateLevelInDict(Dictionary<string, string> featureDict, int currLevel) | |
{ | |
PlayerModel shipToUpgrade = PlayerController.Instance.Ship; | |
Dictionary<string, string> updatedShipLevels = new Dictionary<string, string>(); | |
foreach (var kvp in featureDict) | |
{ | |
string itemKey = kvp.Key; | |
string itemLevel = kvp.Value; | |
if (itemKey == shipToUpgrade.itemID) | |
{ | |
currLevel += 1; | |
updatedShipLevels.Add(itemKey, currLevel + ""); | |
} | |
else | |
{ | |
updatedShipLevels.Add(itemKey, itemLevel); | |
} | |
} | |
return updatedShipLevels; | |
} | |
public void SaveData(bool toCloud = false) | |
{ | |
SaveLocalPlayerData(); | |
if (toCloud) | |
PFMgr.Instance.SaveUserData(PlayerDataToDict()); | |
} | |
void SaveLocalPlayerData() | |
{ | |
//PFData | |
PlayerPrefsX.SetString(Constants.PF_PlayFabID, PFMgr.PF_playFabID); | |
PlayerPrefsX.SetString(Constants.PF_UserName, PFMgr.PF_userName); | |
PlayerPrefsX.SetString(Constants.PF_DisplayName, PFMgr.PF_diplayName); | |
PlayerPrefsX.SetString(Constants.PF_EmailID, PFMgr.PF_email); | |
PlayerPrefsX.SetInt(Constants.PF_AuthType, (int)PFMgr.PF_AuthType); | |
PlayerPrefsX.SetString(Constants.PF_FBAuthToken, PFMgr.FB_AuthToken); | |
// //Settings | |
PlayerPrefsX.SetBool(Constants.D_SoundEnabled, sfxEnabled); | |
PlayerPrefsX.SetBool(Constants.D_MusicEnabled, musicEnabled); | |
PlayerPrefsX.SetBool(Constants.D_FPVEnabled, zoomEnabled); | |
PlayerPrefsX.SetBool(Constants.D_TiltEnabled, tiltEnabled); | |
// //PlayerProgress | |
PlayerPrefsX.SetInt(Constants.PD_PlayerLevel, DBMgr.PlayerLevel); | |
PlayerPrefsX.SetString(Constants.PD_LastPlayedShipID, lastPlayedShipID); | |
PlayerPrefsX.SetStringArray(Constants.PD_PlayerShipInventory, ownedShips); | |
PlayerPrefsX.SetStringArray(Constants.PD_PlayerShipsUnlocked, unlockedShips); | |
PlayerPrefsX.SetIntArray(Constants.PD_ShipThrustLevels, shipThrustLevels); | |
PlayerPrefsX.SetIntArray(Constants.PD_ShipSmashLevels, shipSpeedLevels); | |
PlayerPrefsX.SetIntArray(Constants.PD_ShipHandlingLevels, shipHandlingLevels); | |
PlayerPrefsX.SetString(Constants.PD_LastPlayedShipID, lastPlayedShipID); | |
PlayerPrefs.Save(); | |
} | |
public void SavePermanantIAP() | |
{ | |
PlayerPrefsX.SetBool(Constants.IAP_NOAds, DBMgr.hasNoAdsPack);//InventoryItemCount(Constants.IAP_NOAds) > 0; | |
PlayerPrefsX.SetBool(Constants.IAP_starterPack, DBMgr.hasStarterPack); //InventoryItemCount(Constants.IAP_starterPack) > 0; | |
PlayerPrefsX.SetBool(Constants.IAP_coin_doubler, DBMgr.hasCoinDoublerPack);// InventoryItemCount(Constants.IAP_coin_doubler) > 0; | |
} | |
public void LoadPermanantIAP() | |
{ | |
DBMgr.hasNoAdsPack = PlayerPrefsX.GetBool(Constants.IAP_NOAds, false);//InventoryItemCount(Constants.IAP_NOAds) > 0; | |
DBMgr.hasStarterPack = PlayerPrefsX.GetBool(Constants.IAP_starterPack, false); //InventoryItemCount(Constants.IAP_starterPack) > 0; | |
DBMgr.hasCoinDoublerPack = PlayerPrefsX.GetBool(Constants.IAP_coin_doubler, false);// InventoryItemCount(Constants.IAP_coin_doubler) > 0; | |
} | |
Dictionary<string, string> PlayerDataToDict() | |
{ | |
Dictionary<string, string> DataDict = new Dictionary<string, string>() | |
{ | |
{Constants.PD_LastPlayedShipID,PlayerPrefsX.GetString(Constants.PD_LastPlayedShipID)}, | |
{Constants.PD_ClientVersionUsed,Application.version}, | |
{Constants.PD_ClientBundleID,Application.bundleIdentifier}, | |
// Ship Progress | |
{Constants.PD_ShipThrustLevels,PlayerPrefsX.GetIntArrayCSV(Constants.PD_ShipThrustLevels)}, | |
{Constants.PD_ShipSmashLevels,PlayerPrefsX.GetIntArrayCSV(Constants.PD_ShipSmashLevels)}, | |
{Constants.PD_ShipHandlingLevels,PlayerPrefsX.GetIntArrayCSV(Constants.PD_ShipHandlingLevels)}, | |
}; | |
return DataDict; | |
} | |
public void OnResetAllData() | |
{ | |
DBMgr.Instance.ResetLocalData(); | |
Application.Quit(); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/////////////////////////////////////////////////////////////////////////////////////////////////////// | |
//// | |
// Cloud Script runs in the PlayFab cloud and has full access to the PlayFab Game Server API | |
// (https://api.playfab.com/Documentation/Server), and it runs in the context of a securely | |
// authenticated player, so you can use it to implement logic for your game that is safe from | |
// client-side exploits. | |
// | |
// Cloud Script functions can also make web requests to external HTTP | |
// endpoints, such as a database or private API for your title, which makes them a flexible | |
// way to integrate with your existing backend systems. | |
// | |
// There are several different options for calling Cloud Script functions: | |
// | |
// 1) Your game client calls them directly using the "ExecuteCloudScript" API, | |
// passing in the function name and arguments in the request and receiving the | |
// function return result in the response. | |
// (https://api.playfab.com/Documentation/Client/method/ExecuteCloudScript) | |
// | |
// 2) You create PlayStream event actions that call them when a particular | |
// event occurs, passing in the event and associated player profile data. | |
// (https://api.playfab.com/playstream/docs) | |
// | |
// 3) For titles using the Photon Add-on (https://playfab.com/marketplace/photon/), | |
// Photon room events trigger webhooks which call corresponding Cloud Script functions. | |
// | |
// The following examples demonstrate all three options. | |
// | |
/////////////////////////////////////////////////////////////////////////////////////////////////////// | |
// This is a simple example of making a PlayFab server API call | |
handlers.makeAPICall = function (args, context) { | |
} | |
// This is a simple example of making a PlayFab server API call | |
handlers.updateSoloStats = function (args, context) { | |
var newXP = Math.ceil(args.Scored + (args.Spelled * 100)); | |
var playerStatResult = server.UpdatePlayerStatistics ( | |
{ | |
PlayFabId: currentPlayerId, | |
Statistics: [ | |
{ | |
"StatisticName": "LB_RecordDistance", | |
"Value": args.Surfed | |
}, | |
{ | |
"StatisticName": "LB_RecordSmashScore", | |
"Value": args.Scored | |
}, | |
{ | |
"StatisticName": "TotalCrashes", | |
"Value": 1 | |
}, | |
{ | |
"StatisticName": "TotalSmashes", | |
"Value": args.Smashed | |
}, | |
{ | |
"StatisticName": "TotalDistance", | |
"Value": args.Surfed | |
}, | |
{ | |
"StatisticName": "TotalWords", | |
"Value": args.Spelled | |
}, | |
{ | |
"StatisticName": "HighScore", | |
"Value": args.Scored | |
}, | |
{ | |
"StatisticName": "TopSmasher", | |
"Value": args.Smashed | |
}, | |
{ | |
"StatisticName": "TopSurfer", | |
"Value": args.Surfed | |
}, | |
{ | |
"StatisticName": "WordMaker", | |
"Value": args.Spelled | |
}, | |
{ | |
"StatisticName": "XP", | |
"Value": newXP | |
} | |
] | |
} | |
); | |
//Lets update coins, if greater than zero | |
if(args.Smash >0) | |
{ | |
var addVC = server.AddUserVirtualCurrency({ | |
PlayFabId: currentPlayerId, | |
VirtualCurrency: "GO", | |
Amount: args.Smash | |
}); | |
} | |
//Lets update Gems, is greater than zero | |
if(args.Till >0) | |
{ | |
var addVC = server.AddUserVirtualCurrency({ | |
PlayFabId: currentPlayerId, | |
VirtualCurrency: "GE", | |
Amount: args.Till | |
}); | |
} | |
//Lets update Trophy is greater then zero | |
if(args.You >0) | |
{ | |
var addVC = server.AddUserVirtualCurrency({ | |
PlayFabId: currentPlayerId, | |
VirtualCurrency: "TR", | |
Amount: args.You | |
}); | |
} | |
return { externalAPIResponse: playerStatResult }; | |
} | |
// This is a simple example of making a PlayFab server API call | |
handlers.yoloWatcher = function (args, context) { | |
// The server API can add virtual currency safely | |
var addGoldResult = server.AddUserVirtualCurrency({ | |
PlayFabId: currentPlayerId, | |
VirtualCurrency: args.What, | |
Amount: args.Yolo | |
}); | |
return { responseContent: addGoldResult }; | |
} | |
// This is a simple example of making a PlayFab server API call | |
handlers.modGodVC = function (args, context) { | |
// The server API can add virtual currency safely | |
var addVCResult = server.AddUserVirtualCurrency({ | |
PlayFabId: currentPlayerId, | |
VirtualCurrency: args.What, | |
Amount: args.Yolo | |
}); | |
return { responseContent: addVCResult }; | |
} | |
// This is a simple example of making a PlayFab server API call | |
handlers.modEvilVC = function (args, context) { | |
// The server API can add virtual currency safely | |
var subVCResult = server.SubtractUserVirtualCurrency({ | |
PlayFabId: currentPlayerId, | |
VirtualCurrency: args.What, | |
Amount: args.Yolo | |
}); | |
return { responseContent: subVCResult }; | |
} | |
// This is a simple example of making a PlayFab server API call | |
handlers.fixNegativeCurrFromClient = function (args, context) { | |
//Lets update coins, if greater than zero | |
if(args.Smash <0) | |
{ | |
var addVC = server.AddUserVirtualCurrency({ | |
PlayFabId: currentPlayerId, | |
VirtualCurrency: "GO", | |
Amount: -args.Smash | |
}); | |
} | |
//Lets update Gems, is greater than zero | |
if(args.Till <0) | |
{ | |
var addVC = server.AddUserVirtualCurrency({ | |
PlayFabId: currentPlayerId, | |
VirtualCurrency: "GE", | |
Amount: -args.Till | |
}); | |
} | |
//Lets update Trophy is greater then zero | |
if(args.You <0) | |
{ | |
var addVC = server.AddUserVirtualCurrency({ | |
PlayFabId: currentPlayerId, | |
VirtualCurrency: "TR", | |
Amount: -args.You | |
}); | |
} | |
//return { responseContent: subVCResult }; | |
} | |
handlers.yoloWatcher = function (args, context) { | |
// The server API can add virtual currency safely | |
var addGoldResult = server.AddUserVirtualCurrency({ | |
PlayFabId: currentPlayerId, | |
VirtualCurrency: args.What, | |
Amount: args.Yolo | |
}); | |
return { responseContent: addGoldResult }; | |
} | |
// This is a simple example of making a PlayFab server API call | |
handlers.modGodVC = function (args, context) { | |
// The server API can add virtual currency safely | |
var addVCResult = server.AddUserVirtualCurrency({ | |
PlayFabId: currentPlayerId, | |
VirtualCurrency: args.What, | |
Amount: args.Yolo | |
}); | |
return { responseContent: addVCResult }; | |
} | |
// This is a simple example of making a PlayFab server API call | |
handlers.modEvilVC = function (args, context) { | |
// The server API can add virtual currency safely | |
var subVCResult = server.SubtractUserVirtualCurrency({ | |
PlayFabId: currentPlayerId, | |
VirtualCurrency: args.What, | |
Amount: args.Yolo | |
}); | |
return { responseContent: subVCResult }; | |
} | |
// This is a simple example of making a PlayFab server API call | |
handlers.fixNegativeSegment = function (args, context) { | |
var userCurrencyResult = server.GetPlayerCombinedInfo({ | |
PlayFabId: currentPlayerId, | |
InfoRequestParameters: {"GetUserVirtualCurrency": true} | |
}); | |
var gems = userCurrencyResult.InfoResultPayload.UserVirtualCurrency.GE; | |
var coins = userCurrencyResult.InfoResultPayload.UserVirtualCurrency.GO; | |
var trophy = userCurrencyResult.InfoResultPayload.UserVirtualCurrency.TR; | |
var resonseStr = "Fixing currency: "; | |
//Lets update coins, if greater than zero | |
if(coins && coins <0) | |
{ | |
resonseStr = "Coins: "+coins; | |
var addVC = server.AddUserVirtualCurrency({ | |
PlayFabId: currentPlayerId, | |
VirtualCurrency: "GO", | |
Amount: -coins | |
}); | |
} | |
//Lets update Gems, is greater than zero | |
if(gems && gems <0) | |
{ | |
resonseStr += "Gems: "+gems; | |
var addVC = server.AddUserVirtualCurrency({ | |
PlayFabId: currentPlayerId, | |
VirtualCurrency: "GE", | |
Amount: -gems | |
}); | |
} | |
//Lets update Trophy is greater then zero | |
if(trophy && trophy < 0) | |
{ | |
resonseStr += "Trophy: "+trophy; | |
var addVC = server.AddUserVirtualCurrency({ | |
PlayFabId: currentPlayerId, | |
VirtualCurrency: "TR", | |
Amount: -trophy | |
}); | |
} | |
return { responseContent: resonseStr }; | |
} | |
// This is a simple example of making a PlayFab server API call | |
handlers.fixCrazyNegativeSegment = function (args, context) { | |
var userCurrencyResult = server.GetPlayerCombinedInfo({ | |
PlayFabId: currentPlayerId, | |
InfoRequestParameters: {"GetUserVirtualCurrency": true} | |
}); | |
var gems = userCurrencyResult.InfoResultPayload.UserVirtualCurrency.GE; | |
var coins = userCurrencyResult.InfoResultPayload.UserVirtualCurrency.GO; | |
var trophy = userCurrencyResult.InfoResultPayload.UserVirtualCurrency.TR; | |
var isCrazy = ((gems < -50) || (coins < -50) || (trophy < -50)); | |
var resonseStr = "Fixing currency: "; | |
//Lets update coins, if greater than zero | |
if(coins && coins <-50) | |
{ | |
resonseStr = "Coins: "+coins; | |
var addVC = server.AddUserVirtualCurrency({ | |
PlayFabId: currentPlayerId, | |
VirtualCurrency: "GO", | |
Amount: -coins | |
}); | |
} | |
//Lets update Gems, is greater than zero | |
if(gems && gems <-50) | |
{ | |
resonseStr += "Gems: "+gems; | |
var addVC = server.AddUserVirtualCurrency({ | |
PlayFabId: currentPlayerId, | |
VirtualCurrency: "GE", | |
Amount: -gems | |
}); | |
} | |
//Lets update Trophy is greater then zero | |
if(trophy && trophy < -50) | |
{ | |
resonseStr += "Trophy: "+trophy; | |
var addVC = server.AddUserVirtualCurrency({ | |
PlayFabId: currentPlayerId, | |
VirtualCurrency: "TR", | |
Amount: -trophy | |
}); | |
} | |
if(isCrazy) | |
{ | |
//ShipHandlingLevels >> 0,0,0,0,0,0,0,0,0,0,0,0,0,0 | |
//ShipSpeedLevels >> 0,0,0,0,0,0,0,0,0,0,0,0,0,0 | |
//ShipThrustLevels >> 0,0,0,0,0,0,0,0,0,0,0,0,0,0 | |
//PlayerShipInventory >> ship_0 | |
//PlayerShipsUnlocked >> ship_0 | |
//LastPlayedShipID >> ship_0 | |
var resetUserData = server.UpdateUserData({ | |
PlayFabId: currentPlayerId, | |
Data: { | |
ShipHandlingLevels: "0,0,0,0,0,0,0,0,0,0,0,0,0,0", | |
ShipSpeedLevels:"0,0,0,0,0,0,0,0,0,0,0,0,0,0", | |
ShipThrustLevels:"0,0,0,0,0,0,0,0,0,0,0,0,0,0", | |
PlayerShipInventory:"ship_0", | |
PlayerShipsUnlocked:"ship_0", | |
LastPlayedShipID:"ship_0" | |
}, | |
Permission: "Private" | |
}); | |
} | |
return { responseContent: resonseStr }; | |
} | |
// This is a simple example of making a web request to an external HTTP API. | |
handlers.makeHTTPRequest = function (args, context) { | |
var headers = { | |
"X-MyCustomHeader": "Some Value" | |
}; | |
var body = { | |
input: args, | |
userId: currentPlayerId, | |
mode: "foobar" | |
}; | |
var url = "http://httpbin.org/status/200"; | |
var content = JSON.stringify(body); | |
var httpMethod = "post"; | |
var contentType = "application/json"; | |
var logRequestAndResponse = true; | |
// The pre-defined http object makes synchronous HTTP requests | |
var response = http.request(url, httpMethod, content, contentType, headers, logRequestAndResponse); | |
return { responseContent: response }; | |
} | |
// This is a simple example of a function that is called from a | |
// PlayStream event action. (https://playfab.com/introducing-playstream/) | |
handlers.handlePlayStreamEventAndProfile = function (args, context) { | |
// The event that triggered the action | |
// (https://api.playfab.com/playstream/docs/PlayStreamEventModels) | |
var psEvent = context.playStreamEvent; | |
// The profile data of the player associated with the event | |
// (https://api.playfab.com/playstream/docs/PlayStreamProfileModels) | |
var profile = context.playerProfile; | |
// Post data about the event to an external API | |
var content = JSON.stringify({user: profile.PlayerId, event: psEvent.EventName}); | |
var response = http.request('https://httpbin.org/status/200', 'post', content, 'application/json', null, true); | |
return { externalAPIResponse: response }; | |
} | |
// Below are some examples of using Cloud Script in slightly more realistic scenarios | |
// This is a function that the game client would call whenever a player completes | |
// a level. It updates a setting in the player's data that only game server | |
// code can write - it is read-only on the client - and it updates a player | |
// statistic that can be used for leaderboards. | |
// | |
// A funtion like this could be extended to perform validation on the | |
// level completion data to detect cheating. It could also do things like | |
// award the player items from the game catalog based on their performance. | |
handlers.completedLevel = function (args, context) { | |
var level = args.levelName; | |
var monstersKilled = args.monstersKilled; | |
var updateUserDataResult = server.UpdateUserInternalData({ | |
PlayFabId: currentPlayerId, | |
Data: { | |
lastLevelCompleted: level | |
} | |
}); | |
log.debug("Set lastLevelCompleted for player " + currentPlayerId + " to " + level); | |
server.UpdateUserStatistics({ | |
PlayFabId: currentPlayerId, | |
UserStatistics: { | |
level_monster_kills: monstersKilled | |
} | |
}); | |
log.debug("Updated level_monster_kills stat for player " + currentPlayerId + " to " + monstersKilled); | |
} | |
// In addition to the Cloud Script handlers, you can define your own functions and call them from your handlers. | |
// This makes it possible to share code between multiple handlers and to improve code organization. | |
handlers.updatePlayerMove = function (args) { | |
var validMove = processPlayerMove(args); | |
return { validMove: validMove }; | |
} | |
// This is a helper function that verifies that the player's move wasn't made | |
// too quickly following their previous move, according to the rules of the game. | |
// If the move is valid, then it updates the player's statistics and profile data. | |
// This function is called from the "UpdatePlayerMove" handler above and also is | |
// triggered by the "RoomEventRaised" Photon room event in the Webhook handler | |
// below. | |
// | |
// For this example, the script defines the cooldown period (playerMoveCooldownInSeconds) | |
// as 15 seconds. A recommended approach for values like this would be to create them in Title | |
// Data, so that they can be queries in the script with a call to GetTitleData | |
// (https://api.playfab.com/Documentation/Server/method/GetTitleData). This would allow you to | |
// make adjustments to these values over time, without having to edit, test, and roll out an | |
// updated script. | |
function processPlayerMove(playerMove) { | |
var now = Date.now(); | |
var playerMoveCooldownInSeconds = 15; | |
var playerData = server.GetUserInternalData({ | |
PlayFabId: currentPlayerId, | |
Keys: ["last_move_timestamp"] | |
}); | |
var lastMoveTimestampSetting = playerData.Data["last_move_timestamp"]; | |
if (lastMoveTimestampSetting) { | |
var lastMoveTime = Date.parse(lastMoveTimestampSetting.Value); | |
var timeSinceLastMoveInSeconds = (now - lastMoveTime) / 1000; | |
log.debug("lastMoveTime: " + lastMoveTime + " now: " + now + " timeSinceLastMoveInSeconds: " + timeSinceLastMoveInSeconds); | |
if (timeSinceLastMoveInSeconds < playerMoveCooldownInSeconds) { | |
log.error("Invalid move - time since last move: " + timeSinceLastMoveInSeconds + "s less than minimum of " + playerMoveCooldownInSeconds + "s.") | |
return false; | |
} | |
} | |
var playerStats = server.GetUserStatistics({ | |
PlayFabId: currentPlayerId | |
}).UserStatistics; | |
if (playerStats.movesMade) | |
playerStats.movesMade += 1; | |
else | |
playerStats.movesMade = 1; | |
server.UpdateUserStatistics({ | |
PlayFabId: currentPlayerId, | |
UserStatistics: playerStats | |
}); | |
server.UpdateUserInternalData({ | |
PlayFabId: currentPlayerId, | |
Data: { | |
last_move_timestamp: new Date(now).toUTCString(), | |
last_move: JSON.stringify(playerMove) | |
} | |
}); | |
return true; | |
} | |
// This is an example of using PlayStream real-time segmentation to trigger | |
// game logic based on player behavior. (https://playfab.com/introducing-playstream/) | |
// The function is called when a player_statistic_changed PlayStream event causes a player | |
// to enter a segment defined for high skill players. It sets a key value in | |
// the player's internal data which unlocks some new content for the player. | |
handlers.unlockHighSkillContent = function(args, context) | |
{ | |
var playerStatUpdatedEvent = context.playStreamEvent; | |
var playerInternalData = server.UpdateUserInternalData( | |
{ | |
PlayFabId: currentPlayerId, | |
"Data": { | |
"HighSkillContent": true, | |
"XPAtHighSkillUnlock": playerStatUpdatedEvent.StatisticValue | |
} | |
}); | |
log.info('Unlocked HighSkillContent for ' + context.playerProfile.DisplayName); | |
return { profile: context.playerProfile }; | |
} | |
// Photon Webhooks Integration | |
// | |
// The following functions are examples of Photon Cloud Webhook handlers. | |
// When you enable the Photon Add-on (https://playfab.com/marketplace/photon/) | |
// in the Game Manager, your Photon applications are automatically configured | |
// to authenticate players using their PlayFab accounts and to fire events that | |
// trigger your Cloud Script Webhook handlers, if defined. | |
// This makes it easier than ever to incorporate multiplayer server logic into your game. | |
// Triggered automatically when a Photon room is first created | |
handlers.RoomCreated = function (args) { | |
log.debug("Room Created - Game: " + args.GameId + " MaxPlayers: " + args.CreateOptions.MaxPlayers); | |
} | |
// Triggered automatically when a player joins a Photon room | |
handlers.RoomJoined = function (args) { | |
log.debug("Room Joined - Game: " + args.GameId + " PlayFabId: " + args.UserId); | |
} | |
// Triggered automatically when a player leaves a Photon room | |
handlers.RoomLeft = function (args) { | |
log.debug("Room Left - Game: " + args.GameId + " PlayFabId: " + args.UserId); | |
} | |
// Triggered automatically when a Photon room closes | |
// Note: currentPlayerId is undefined in this function | |
handlers.RoomClosed = function (args) { | |
log.debug("Room Closed - Game: " + args.GameId); | |
} | |
// Triggered automatically when a Photon room game property is updated. | |
// Note: currentPlayerId is undefined in this function | |
handlers.RoomPropertyUpdated = function(args) { | |
log.debug("Room Property Updated - Game: " + args.GameId); | |
} | |
// Triggered by calling "OpRaiseEvent" on the Photon client. The "args.Data" property is | |
// set to the value of the "customEventContent" HashTable parameter, so you can use | |
// it to pass in arbitrary data. | |
handlers.RoomEventRaised = function (args) { | |
var eventData = args.Data; | |
log.debug("Event Raised - Game: " + args.GameId + " Event Type: " + eventData.eventType); | |
switch (eventData.eventType) { | |
case "playerMove": | |
processPlayerMove(eventData); | |
break; | |
default: | |
break; | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using UnityEngine; | |
using System.Collections; | |
using System.Collections.Generic; | |
using System.Linq; | |
using Facebook.Unity; | |
using Facebook.MiniJSON; | |
using UnityEngine.Purchasing; | |
//PlayFab | |
using PlayFab; | |
using PlayFab.ClientModels; | |
using CodeStage.AntiCheat.ObscuredTypes; | |
public class PFMgr : MonoBehaviour | |
{ | |
public static PFMgr Instance; | |
public delegate void FacebookLinkAccountSuccess(); | |
public static event FacebookLinkAccountSuccess FBLinkAccountSuccessEvent; | |
public delegate void LoginSuccess(); | |
public static event LoginSuccess LoginSuccessEvent; | |
public delegate void UseDataReceived(); | |
public static event UseDataReceived UseDataRecievedEvent; | |
public delegate void UserInventoryUpdated(); | |
public static event UserInventoryUpdated UserInventoryUpdatedEvent; | |
public delegate void UserStatsUpdated(); | |
public static event UserStatsUpdated UserStatsUpdatedEvent; | |
public delegate void CatalogUpdated(); | |
public static event CatalogUpdated CatalogItemsUpdatedEvent; | |
public delegate void StoreItemsUpdated(); | |
public static event StoreItemsUpdated StoreItemsUpdatedEvent; | |
public delegate void PlayerDataSavedToCloud(); | |
public static event PlayerDataSavedToCloud PlayerDataSavedToCloudEvent; | |
public delegate void PlayerDataSaveError(); | |
public static event PlayerDataSaveError PlayerDataSaveErrorEvent; | |
public delegate void LBDataReceived(); | |
public static event LBDataReceived LBDataReceivedEvent; | |
/// <summary> | |
/// Easy Access | |
/// </summary> | |
private List<ItemInstance> userInventory = null; | |
private List<CatalogItem> catalogItems = null; | |
private List<StoreItem> shipStoreItems = null; | |
private List<StoreItem> coinStoreItems = null; | |
private List<StoreItem> IAPStoreItems = null; | |
//private List<StatisticValue> playerStatistics = null; | |
public List<PlayerLeaderboardEntry> WeeklyTopScoreLB = null; | |
public List<PlayerLeaderboardEntry> AllTimeHighScoreLB = null; | |
public enum AUTH_TYPE | |
{ | |
LOGIN_CHOOSE = -1, | |
LOGIN_FAUNAFACE = 0, //Email & Password | |
LOGIN_FACEBOOK = 1, //FbAuthToken? | |
LOGIN_GAMECENTER = 2, | |
LOGIN_GOOGLE = 3, | |
LOGIN_IOS = 4, | |
LOGIN_ANDROID = 5, | |
LOGIN_STEAM = 5, | |
LOGIN_KONGREGATE = 6, | |
LOGIN_CUSTOM = 7, | |
LOGIN_DEVICE = 8, | |
} | |
///// PlayFab | |
public static ObscuredString PF_TitleId = "93A3"; | |
public static ObscuredString PF_playFabID = string.Empty; | |
public static ObscuredString PF_userName = string.Empty; | |
public static ObscuredString PF_diplayName = string.Empty; | |
public static ObscuredString PF_email = string.Empty; | |
public static ObscuredString PF_FB_ID = string.Empty; | |
public static ObscuredString PF_FB_Name = string.Empty; | |
public static ObscuredString FB_AuthToken = string.Empty; | |
public static AUTH_TYPE PF_AuthType = AUTH_TYPE.LOGIN_CHOOSE; | |
public static bool IsLogErrorInProgress = false; | |
public static bool IsPurchaseItemInProgress = false; | |
public static bool IsSavePlayerDateInProgress = false; | |
/// <summary> | |
/// IAP package Status | |
/// </summary> | |
void Awake() | |
{ | |
DontDestroyOnLoad(transform.root.gameObject); | |
Instance = this; | |
//// PlayFab | |
PlayFabSettings.TitleId = PF_TitleId; | |
//PF_userID = PlayerPrefs.GetString(Constants.PF_USERID); | |
PF_playFabID = PlayerPrefsX.GetString(Constants.PF_PlayFabID, PF_playFabID); | |
PF_userName = PlayerPrefsX.GetString(Constants.PF_UserName, PF_userName); | |
PF_diplayName = PlayerPrefsX.GetString(Constants.PF_DisplayName, PF_diplayName); | |
PF_email = PlayerPrefsX.GetString(Constants.PF_EmailID, PF_email); | |
//Load AuthType and FBAuth Token | |
PF_AuthType = (PFMgr.AUTH_TYPE)PlayerPrefsX.GetInt(Constants.PF_AuthType, (int)PF_AuthType); | |
FB_AuthToken = PlayerPrefsX.GetString(Constants.PF_FBAuthToken, FB_AuthToken); | |
} | |
// void Start() | |
// { | |
// //PlayFabLogInWithDeviceID(); | |
// } | |
public static bool IsLoggedIn | |
{ | |
get { return PlayFabClientAPI.IsClientLoggedIn(); } | |
} | |
public string SocialName | |
{ | |
get { return IsFBLinked ? PF_FB_Name.ToString() : "You"; } | |
} | |
public bool IsFBLinked | |
{ | |
get { return !string.IsNullOrEmpty(PF_FB_ID); } | |
} | |
/// <summary> | |
/// Helper functions | |
/// </summary> | |
/// <param name="key">Key.</param> | |
public void UpdateDurableItemStatus() | |
{ | |
DBMgr.hasNoAdsPack = InventoryItemCount(Constants.IAP_NOAds) > 0; | |
DBMgr.hasStarterPack = InventoryItemCount(Constants.IAP_starterPack) > 0; | |
DBMgr.hasCoinDoublerPack = InventoryItemCount(Constants.IAP_coin_doubler) > 0; | |
DBMgr.Log(">>> Durable Pack Status >>"); | |
DBMgr.Log(">> No Ads pack: " + DBMgr.hasNoAdsPack); | |
DBMgr.Log(">> Starter Pack: " + DBMgr.hasStarterPack); | |
DBMgr.Log(">> CoinDoubler Pack: " + DBMgr.hasCoinDoublerPack); | |
DBMgr.Log(">> >> >> >> >> >> >> >> >> >>"); | |
DBMgr.Instance.SavePermanantIAP(); | |
} | |
public int InventoryItemCount(string itemID) | |
{ | |
int itemCount = 0; | |
if (userInventory != null) | |
{ | |
foreach (ItemInstance item in userInventory) | |
itemCount += string.Equals(item.ItemId, itemID) ? 1 : 0; | |
} | |
return itemCount; | |
} | |
public StoreItem GetStoreItemForShipID(string itemID) | |
{ | |
StoreItem item = null; | |
if (shipStoreItems != null) | |
{ | |
foreach (StoreItem storeItem in shipStoreItems) | |
{ | |
if (string.Equals(itemID, storeItem.ItemId)) | |
{ | |
item = storeItem; | |
break; | |
} | |
} | |
} | |
return item; | |
} | |
public StoreItem GetIAPItemForID(string itemID) | |
{ | |
StoreItem item = null; | |
if (IAPStoreItems != null) | |
{ | |
foreach (StoreItem storeItem in IAPStoreItems) | |
{ | |
if (string.Equals(itemID, storeItem.ItemId)) | |
{ | |
item = storeItem; | |
break; | |
} | |
} | |
} | |
return item; | |
} | |
public StoreItem GetCoinItemForID(string itemID) | |
{ | |
StoreItem item = null; | |
if (coinStoreItems != null) | |
{ | |
foreach (StoreItem storeItem in coinStoreItems) | |
{ | |
if (string.Equals(itemID, storeItem.ItemId)) | |
{ | |
item = storeItem; | |
break; | |
} | |
} | |
} | |
return item; | |
} | |
public CatalogItem GetCatalogItemForID(string itemID) | |
{ | |
CatalogItem item = null; | |
if (catalogItems != null) | |
{ | |
foreach (CatalogItem catalogItem in catalogItems) | |
{ | |
if (string.Equals(itemID, catalogItem.ItemId)) | |
{ | |
item = catalogItem; | |
break; | |
} | |
} | |
} | |
return item; | |
} | |
void UpdateIntFromDict(string key, Dictionary<string, string> data, Dictionary<string, UserDataRecord> rec = null) | |
{ | |
string value = string.Empty; | |
UserDataRecord recVal = null; | |
int serverValue; | |
if (data != null && data.TryGetValue(key, out value)) | |
{ | |
int.TryParse(value, out serverValue); | |
//Debug.Log("Int: UpdateIntFromDict >>> Key "+key+" Value: "+serverValue); | |
PlayerPrefsX.SetInt(key, serverValue); | |
} | |
else if (rec != null && rec.TryGetValue(key, out recVal)) | |
{ | |
int.TryParse(recVal.Value, out serverValue); | |
// Debug.Log("Int: UpdateIntFromDict >>> Key "+key+" Value: "+serverValue); | |
PlayerPrefsX.SetInt(key, serverValue); | |
} | |
} | |
void UpdateIntArrayFromDict(string key, Dictionary<string, string> data, Dictionary<string, UserDataRecord> rec = null) | |
{ | |
string serverValue = string.Empty; | |
UserDataRecord recVal = null; | |
if (data != null && data.TryGetValue(key, out serverValue)) | |
{ | |
//Debug.Log("INT[] : UpdateIntArrayFromDict>>> Key "+key+" Value: "+serverValue); | |
PlayerPrefsX.SetIntArrayCSV(key, serverValue); | |
} | |
else if (rec != null && rec.TryGetValue(key, out recVal)) | |
{ | |
//Debug.Log("INT[] : UpdateIntArrayFromDict>>> Key "+key+" Value: "+serverValue); | |
PlayerPrefsX.SetIntArrayCSV(key, recVal.Value); | |
} | |
} | |
void UpdateFloatFromDict(string key, Dictionary<string, string> data, Dictionary<string, UserDataRecord> rec = null) | |
{ | |
string value = string.Empty; | |
UserDataRecord recVal = null; | |
float serverValue; | |
if (data != null && data.TryGetValue(key, out value)) | |
{ | |
float.TryParse(value, out serverValue); | |
//Debug.Log("Float: UpdateFloatFromDict >>> Key "+key+" Value: "+serverValue + " Value: "+value ); | |
PlayerPrefs.SetFloat(key, serverValue); | |
} | |
else if (rec != null && rec.TryGetValue(key, out recVal)) | |
{ | |
float.TryParse(recVal.Value, out serverValue); | |
//Debug.Log("Int: UpdateIntFromDict >>> Key "+key+" Value: "+serverValue); | |
PlayerPrefs.SetFloat(key, serverValue); | |
} | |
} | |
void UpdateFloatArrayFromDict(string key, Dictionary<string, string> data, Dictionary<string, UserDataRecord> rec = null) | |
{ | |
string serverValue = string.Empty; | |
UserDataRecord recVal = null; | |
if (data != null && data.TryGetValue(key, out serverValue)) | |
{ | |
//Debug.Log("FLOAT[] : UpdateFloatArrayFromDict>>> Key "+key+" Value: "+serverValue); | |
PlayerPrefsX.SetFloatArrayCSV(key, serverValue); | |
} | |
else if (rec != null && rec.TryGetValue(key, out recVal)) | |
{ | |
//Debug.Log("FLOAT[] : UpdateFloatArrayFromDict>>> Key "+key+" Value: "+serverValue); | |
PlayerPrefsX.SetFloatArrayCSV(key, recVal.Value); | |
} | |
} | |
void UpdateBoolFromDict(string key, Dictionary<string, string> data, Dictionary<string, UserDataRecord> rec = null) | |
{ | |
string serverValue = string.Empty; | |
UserDataRecord recVal = null; | |
if (data != null && data.TryGetValue(key, out serverValue)) | |
{ | |
bool isTrue = serverValue.Equals("True"); | |
PlayerPrefsX.SetBool(key, isTrue); | |
} | |
else if (rec != null && rec.TryGetValue(key, out recVal)) | |
{ | |
bool isTrue = recVal.Value.Equals("True"); | |
PlayerPrefsX.SetBool(key, isTrue); | |
} | |
} | |
void UpdateStringFromDict(string key, Dictionary<string, string> data, Dictionary<string, UserDataRecord> rec = null) | |
{ | |
string serverValue = string.Empty; | |
UserDataRecord recVal = null; | |
if (data != null && data.TryGetValue(key, out serverValue)) | |
{ | |
//Debug.Log("STR: UpdateStringFromDict >>> Key "+key+" Value: "+serverVale); | |
PlayerPrefsX.SetString(key, serverValue); | |
} | |
else if (rec != null && rec.TryGetValue(key, out recVal)) | |
{ | |
//Debug.Log("STR: UpdateStringFromDict >>> Key "+key+" Value: "+recVal.Value); | |
PlayerPrefsX.SetString(key, recVal.Value); | |
} | |
} | |
void UpdateStringArrayFromDict(string key, Dictionary<string, string> data, Dictionary<string, UserDataRecord> rec = null) | |
{ | |
string serverValue = string.Empty; | |
UserDataRecord recVal = null; | |
if (data != null && data.TryGetValue(key, out serverValue)) | |
{ | |
//Debug.Log("STR[] UpdateStringArrayFromDict >>> Key "+key+" Value: "+serverValue); | |
PlayerPrefsX.SetStringArrayCSV(key, serverValue); | |
} | |
else if (rec != null && rec.TryGetValue(key, out recVal)) | |
{ | |
//Debug.Log("STR[] UpdateStringArrayFromDict >>> Key "+key+" Value: "+serverValue); | |
PlayerPrefsX.SetStringArrayCSV(key, recVal.Value); | |
} | |
} | |
void ExtractTitleData(Dictionary<string, string> data) | |
{ | |
// //GameConstants | |
UpdateFloatArrayFromDict(Constants.TD_mulliganConstants, data); | |
// | |
// //Economy | |
UpdateIntFromDict(Constants.TD_gemToCoinConversion, data); | |
UpdateIntFromDict(Constants.TD_gemsPerAdView, data); | |
UpdateIntFromDict(Constants.TD_cameraFOV, data); | |
UpdateFloatArrayFromDict(Constants.TD_cameraZoomLevels, data); | |
UpdateIntArrayFromDict(Constants.TD_boostCostInCoins, data); | |
UpdateIntArrayFromDict(Constants.TD_boostUnlockLevel, data); | |
UpdateStringArrayFromDict(Constants.TD_boostNames, data); | |
UpdateStringArrayFromDict(Constants.TD_boostInfo, data); | |
UpdateIntArrayFromDict(Constants.TD_gameDiffMinTrophy, data); | |
UpdateIntArrayFromDict(Constants.TD_gameDiffEntryCost, data); | |
UpdateIntArrayFromDict(Constants.TD_gameDiffRewardPerWord, data); | |
// | |
UpdateIntFromDict(Constants.TD_MinTrophyForFTUESkip, data); | |
UpdateIntFromDict(Constants.TD_ShowDistStat, data); | |
// | |
// //Social & Sharing features | |
UpdateStringFromDict(Constants.TD_facebookAppID, data); | |
UpdateStringFromDict(Constants.TD_facebookPageURL, data); | |
UpdateStringFromDict(Constants.TD_previewImageURL, data); | |
UpdateStringFromDict(Constants.TD_facebookAppLinkURL, data); | |
UpdateStringFromDict(Constants.TD_iTunesConnectURL, data); | |
UpdateStringFromDict(Constants.TD_gameName, data); | |
UpdateStringFromDict(Constants.TD_gameCaption, data); | |
UpdateStringFromDict(Constants.TD_tweetAddress, data); | |
UpdateStringFromDict(Constants.TD_gameCreditsText, data); | |
UpdateStringFromDict(Constants.TD_copyRightText, data); | |
UpdateStringFromDict(Constants.TD_termsOfService, data); | |
UpdateStringFromDict(Constants.TD_getCardboardURL, data); | |
PlayerPrefs.Save(); | |
//Now that the date is save to the Local Cache.. Lets load the date into the variables that is used by the game. | |
DBMgr.Instance.InitAndLoadLocalTitleData(); | |
Debug.Log(">> Show Dist Stats: " + DBMgr._showDistanceStat); | |
} | |
void UpdatePlayerDataFromServer(Dictionary<string, UserDataRecord> data) | |
{ | |
// //PlayerProgress | |
UpdateIntFromDict(Constants.PD_PlayerLevel, null, data); | |
UpdateStringFromDict(Constants.PD_LastPlayedShipID, null, data); | |
UpdateStringArrayFromDict(Constants.PD_PlayerShipInventory, null, data); | |
UpdateStringArrayFromDict(Constants.PD_PlayerShipsUnlocked, null, data); | |
UpdateIntArrayFromDict(Constants.PD_ShipSmashLevels, null, data); | |
UpdateIntArrayFromDict(Constants.PD_ShipHandlingLevels, null, data); | |
UpdateIntArrayFromDict(Constants.PD_ShipThrustLevels, null, data); | |
PlayerPrefs.Save(); | |
DBMgr.Instance.InitAndLoadPlayerData(); | |
} | |
public void ExtractUserAccountInfo(UserAccountInfo info) | |
{ | |
if (info.Username != null) | |
PF_userName = info.Username; | |
if (info.TitleInfo != null && info.TitleInfo.DisplayName != null) | |
PF_diplayName = info.TitleInfo.DisplayName; | |
if (info.PrivateInfo != null && info.PrivateInfo.Email != null) | |
PF_email = info.PrivateInfo.Email; | |
if (info.PlayFabId != null) | |
PF_playFabID = info.PlayFabId; | |
if (info.FacebookInfo != null && info.FacebookInfo.FacebookId != null) | |
PF_FB_ID = info.FacebookInfo.FacebookId; | |
if (info.FacebookInfo != null && info.FacebookInfo.FullName != null) | |
PF_FB_Name = info.FacebookInfo.FullName; | |
if (UseDataRecievedEvent != null) | |
UseDataRecievedEvent(); | |
// AnalyticsMgr.Instance.LogCustomEvent("UserAuthComplete: ",new Dictionary<string, object> | |
// { | |
// { "userOrigin", info.TitleInfo.Origination.ToString()}, | |
// { "userName", PF_userName}, | |
// { "displayName", PF_diplayName }, | |
// { "playFabID", PF_playFabID} | |
// }); | |
DBMgr.Instance.SaveData(); | |
} | |
public void ExtractPlayerStats(List<StatisticValue> stats) | |
{ | |
foreach (StatisticValue stat in stats) | |
{ | |
//Weekly | |
if (stat.StatisticName == Constants.RecordDistanceLB) | |
DBMgr.RecordDistance = stat.Value; | |
if (stat.StatisticName == Constants.RecordSmashScoreLB) | |
DBMgr.RecordScore = stat.Value; | |
//Totals | |
if (stat.StatisticName == Constants.TotalCrashes) | |
DBMgr.TotalCrashes = stat.Value; | |
if (stat.StatisticName == Constants.TotalDistance) | |
DBMgr.TotalDistance = stat.Value; | |
if (stat.StatisticName == Constants.TotalSmashes) | |
DBMgr.TotalSmashes = stat.Value; | |
if (stat.StatisticName == Constants.TotalWords) | |
DBMgr.TotalWords = stat.Value; | |
//AllTime | |
if (stat.StatisticName == Constants.HighScore) | |
DBMgr.TopScore = stat.Value; | |
if (stat.StatisticName == Constants.TopSmashed) | |
DBMgr.TopSmashed = stat.Value; | |
if (stat.StatisticName == Constants.TopSurfed) | |
DBMgr.TopSurfed = stat.Value; | |
if (stat.StatisticName == Constants.TopWords) | |
DBMgr.TopWords = stat.Value; | |
} | |
if (UserStatsUpdatedEvent != null) | |
UserStatsUpdatedEvent(); | |
} | |
/// <summary> | |
/// Plaies the fab log in with device I. | |
/// </summary> | |
public void LogInWithDeviceID() | |
{ | |
PFMgr.PF_AuthType = PFMgr.AUTH_TYPE.LOGIN_DEVICE; | |
DBMgr.Instance.SaveData(); | |
///// | |
////PlayFab | |
//// | |
//Debug.Log("Starting Auto-login Process"); | |
#if UNITY_IOS || UNITY_TVOS | |
PlayFabClientAPI.LoginWithIOSDeviceID (new LoginWithIOSDeviceIDRequest | |
{ | |
DeviceId = SystemInfo.deviceUniqueIdentifier, | |
OS = SystemInfo.operatingSystem, | |
DeviceModel = SystemInfo.deviceModel, | |
CreateAccount = true | |
}, OnLoginSuccess, OnDeviceLoginError); | |
#elif UNITY_ANDROID | |
PlayFabClientAPI.LoginWithAndroidDeviceID (new LoginWithAndroidDeviceIDRequest | |
{ | |
AndroidDeviceId = SystemInfo.deviceUniqueIdentifier, | |
OS = SystemInfo.operatingSystem, | |
AndroidDevice = SystemInfo.deviceModel, | |
CreateAccount = true | |
}, OnLoginSuccess, OnDeviceLoginError); | |
#elif UNITY_EDITOR | |
PlayFabClientAPI.LoginWithCustomID(new LoginWithCustomIDRequest | |
{ | |
TitleId = PF_TitleId, | |
CustomId = customDevID, | |
CreateAccount = true | |
}, OnLoginSuccess, OnDeviceLoginError); | |
#endif | |
// LoginWithPlayFabRequest req = new LoginWithPlayFabRequest() | |
// { | |
// | |
// } | |
} | |
private void OnLoginSuccess(PlayFab.ClientModels.LoginResult result) | |
{ | |
PF_playFabID = result.PlayFabId; | |
DBMgr.Instance.SaveData(); | |
if (LoginSuccessEvent != null) | |
LoginSuccessEvent(); | |
GetUserCombinedData(true, true, true, true, true, true, true); | |
} | |
public void PurchaseItem(string catalogID, string itemID, string currKey, int price, string storeID, string displayName = "") | |
{ | |
if (!IsLoggedIn && Constants.IsOffline) | |
{ | |
InfoPopup.Instance.ShowMessage("You are Offline ...", 1.0f, 1.0f, Color.red); | |
SoundManager.Instance.PlaySfx("Click_Electronic_16"); | |
return; | |
} | |
if (IsPurchaseItemInProgress) | |
{ | |
InfoPopup.Instance.ShowMessage("Purchase already in Progress", 2.0f, 1.0f, Color.red, false); | |
SoundManager.Instance.PlaySfx("Click_Electronic_16"); | |
return; | |
} | |
IsPurchaseItemInProgress = true; | |
InfoPopup.Instance.TogglePurchaseProgress(IsPurchaseItemInProgress, displayName, Color.yellow); | |
//Lets try purchasing some boost | |
PurchaseItemRequest purchaseItem = new PurchaseItemRequest | |
{ | |
ItemId = itemID, | |
VirtualCurrency = currKey, | |
Price = price, | |
CatalogVersion = catalogID, | |
StoreId = storeID | |
}; | |
PlayFabClientAPI.PurchaseItem(purchaseItem, (result) => | |
{ | |
foreach (ItemInstance item in result.Items) | |
{ | |
if (string.Equals(item.ItemId, itemID) && IsPurchaseItemInProgress) | |
{ | |
IsPurchaseItemInProgress = false; | |
InfoPopup.Instance.TogglePurchaseProgress(IsPurchaseItemInProgress, item.DisplayName + " purchase successful ...", Color.white); | |
SoundManager.Instance.PlaySfx("Click_Electronic_08"); | |
GetUserCombinedData(true, true); | |
break; | |
} | |
} | |
}, (error) => | |
{ | |
IsPurchaseItemInProgress = false; | |
InfoPopup.Instance.TogglePurchaseProgress(IsPurchaseItemInProgress, "Error ", Color.red); | |
OnPurchaseItemError(error, storeID, itemID, price, currKey); | |
}); | |
} | |
public void GetUserCombinedData(bool virtualCurr = true, bool userInv = false, bool userData = false, bool titleData = false, bool accountInfo = false, bool storeData = false, bool stats = false) | |
{ | |
if (!IsLoggedIn) | |
return; | |
Debug.Log("About to request Combined userData: VC" + virtualCurr + " Inv:" + userInv + " userData:" + userData + " titleData:" + titleData + " accountInfo:" + accountInfo + " storeData:" + storeData); | |
GetPlayerCombinedInfoRequestParams userDataParm = new GetPlayerCombinedInfoRequestParams(); | |
userDataParm.GetUserVirtualCurrency = virtualCurr; | |
userDataParm.GetUserInventory = userInv; | |
userDataParm.GetUserAccountInfo = accountInfo; | |
userDataParm.GetTitleData = titleData; | |
userDataParm.GetUserData = userData; | |
userDataParm.GetPlayerStatistics = stats; | |
GetPlayerCombinedInfoRequest request = new GetPlayerCombinedInfoRequest() | |
{ | |
InfoRequestParameters = userDataParm | |
}; | |
PlayFabClientAPI.GetPlayerCombinedInfo(request, (result) => | |
{ | |
if (userData) | |
{ | |
//PlayerData | |
//TODO: Lets assume that we have a oneway sync, for this release. On one device | |
UpdatePlayerDataFromServer(result.InfoResultPayload.UserData); | |
} | |
if (virtualCurr) | |
{ | |
int oldCoins = DBMgr.TotalCoins; | |
int oldGems = DBMgr.TotalGems; | |
int oldTrophy = DBMgr.TotalTrophy; | |
//Virtual Currency | |
Dictionary<string, int> VirtualCurrency = result.InfoResultPayload.UserVirtualCurrency; | |
int totalCoins = 0; | |
int totalGems = 0; | |
int totalTrophy = 0; | |
VirtualCurrency.TryGetValue(Constants.GEM_KEY, out totalGems); | |
VirtualCurrency.TryGetValue(Constants.COIN_KEY, out totalCoins); | |
VirtualCurrency.TryGetValue(Constants.TROPHY_KEY, out totalTrophy); | |
if (totalCoins < 0 || totalGems < 0 || totalTrophy < 0) | |
{ | |
//Possible Hacked Client, Lets call the server to reset VC | |
//FixNegativeCurrencyWithScript(totalCoins,totalGems,totalTrophy); | |
} | |
DBMgr.TotalGems = totalGems; | |
DBMgr.TotalCoins = totalCoins; | |
DBMgr.TotalTrophy = totalTrophy; | |
if (totalCoins > oldCoins) | |
{ | |
if (SoundManager.Instance != null) | |
SoundManager.Instance.PlayElectronicClickSfx("Click_Electronic_08"); | |
InfoPopup.Instance.PunchInfo("Coins +" + (totalCoins - oldCoins), Color.yellow, 1.5f); | |
} | |
if (totalGems > oldGems) | |
{ | |
if (SoundManager.Instance != null) | |
SoundManager.Instance.PlayElectronicClickSfx("Click_Electronic_08"); | |
InfoPopup.Instance.PunchInfo("Gems +" + (totalGems - oldGems), Color.cyan, 1.5f); | |
} | |
} | |
if (titleData) | |
{ | |
DBMgr.Log(">> Extracting Title Data >>"); | |
ExtractTitleData(result.InfoResultPayload.TitleData); | |
DBMgr.Log(">> Title Data Extracted >>"); | |
} | |
if (userInv) | |
{ | |
// User Inventory | |
userInventory = result.InfoResultPayload.UserInventory; | |
UpdateDurableItemStatus(); | |
DBMgr.Log(">> UserInventory Recieved >> " + userInventory.Count); | |
if (UserInventoryUpdatedEvent != null) | |
UserInventoryUpdatedEvent(); | |
} | |
if (storeData) | |
{ | |
//Now let's get the catalog items | |
GetCatalogItems(); | |
GetCoinStoreItems(); | |
GetShipStoreItems(); | |
GetIAPStoreItems(); | |
} | |
if (stats) | |
{ | |
ExtractPlayerStats(result.InfoResultPayload.PlayerStatistics); | |
} | |
try | |
{ | |
if (accountInfo) | |
{ | |
//AccountInfo | |
DBMgr.Log(">> Extracting user Info >>"); | |
ExtractUserAccountInfo(result.InfoResultPayload.AccountInfo); | |
DBMgr.Log(">> User Info Extracted >>"); | |
} | |
} | |
catch | |
{ | |
Debug.LogError("Error tryingh to extract the info"); | |
DBMgr.Log(">>>>> XXX XX XX XX Error extracing Accont info XX X X X XXXXXXX<<<<<<"); | |
} | |
}, OnPlayFabError); | |
} | |
void GetCatalogItems() | |
{ | |
if (!IsLoggedIn) | |
return; | |
GetCatalogItemsRequest request = new GetCatalogItemsRequest() | |
{ | |
CatalogVersion = Constants.CATALOG_VER | |
}; | |
PlayFabClientAPI.GetCatalogItems(request, (result) => | |
{ | |
GetCatalogItemsResult resultData = (GetCatalogItemsResult)result; | |
catalogItems = resultData.Catalog; | |
if (CatalogItemsUpdatedEvent != null) | |
CatalogItemsUpdatedEvent(); | |
DBMgr.Log(">>. CatalogItems Recieved >> " + catalogItems.Count); | |
//Initialize IAP Manager | |
IAPMgr.Instance.Init(); | |
}, OnPlayFabError); | |
} | |
void GetCoinStoreItems() | |
{ | |
if (!IsLoggedIn) | |
return; | |
GetStoreItemsRequest storeReq = new GetStoreItemsRequest | |
{ | |
CatalogVersion = Constants.CATALOG_VER, | |
StoreId = Constants.STORE_COIN | |
}; | |
// Get Store | |
PlayFabClientAPI.GetStoreItems(storeReq, (result) => | |
{ | |
coinStoreItems = result.Store; | |
if (StoreItemsUpdatedEvent != null) | |
StoreItemsUpdatedEvent(); | |
DBMgr.Log(">> CoinStore Items Recieved >> " + coinStoreItems.Count); | |
}, OnPlayFabError); | |
} | |
void GetShipStoreItems() | |
{ | |
if (!IsLoggedIn) | |
return; | |
GetStoreItemsRequest storeReq = new GetStoreItemsRequest | |
{ | |
CatalogVersion = Constants.CATALOG_VER, | |
StoreId = Constants.STORE_SHIP | |
}; | |
// Get Store | |
PlayFabClientAPI.GetStoreItems(storeReq, (result) => | |
{ | |
shipStoreItems = result.Store; | |
if (StoreItemsUpdatedEvent != null) | |
StoreItemsUpdatedEvent(); | |
DBMgr.Log(">> ShipStore Items Recieved >> " + shipStoreItems.Count); | |
}, OnPlayFabError); | |
} | |
void GetIAPStoreItems() | |
{ | |
if (!IsLoggedIn) | |
return; | |
GetStoreItemsRequest storeReq = new GetStoreItemsRequest | |
{ | |
CatalogVersion = Constants.CATALOG_VER, | |
StoreId = Constants.STORE_IAP | |
}; | |
// Get Store | |
PlayFabClientAPI.GetStoreItems(storeReq, (result) => | |
{ | |
IAPStoreItems = result.Store; | |
if (StoreItemsUpdatedEvent != null) | |
StoreItemsUpdatedEvent(); | |
DBMgr.Log(">> IAPStore Items Recieved >> " + IAPStoreItems.Count); | |
}, OnPlayFabError); | |
} | |
public void SubmitPlayerStatsWithScript(int coins, int gems, int trophy, int distance, int score, int smashes, int words, int mull) | |
{ | |
if (!IsLoggedIn) | |
return; | |
if (GameManager.Instance.gameStatsSubmitted) | |
return; | |
ExecuteCloudScriptRequest request = new ExecuteCloudScriptRequest() | |
{ | |
FunctionName = Constants.FUN_UpdateStats, | |
FunctionParameter = new Dictionary<string, object> { | |
{ "Smash", coins}, | |
{ "Till", gems}, | |
{ "You", trophy}, | |
{ "Crash", Random.Range(3,100)}, // This is to confuse | |
{ "Surfed", distance}, //Surfed | |
{ "Scored", score }, //Scored | |
{ "Smashed", smashes}, //Smashed | |
{ "Spelled", words}, //Spelled | |
{ "Mull", mull}, //Mulligans | |
}, | |
RevisionSelection = CloudScriptRevisionOption.Live, | |
GeneratePlayStreamEvent = true | |
}; | |
PlayFabClientAPI.ExecuteCloudScript(request, (result) => | |
{ | |
//Debug.Log("Player Stats updated"); | |
GetUserCombinedData(true, false, false, false, false, false, true); | |
GetUpdatedLeaderboard(); | |
GameManager.Instance.gameStatsSubmitted = true; | |
}, (PlayFabError error) => | |
{ | |
Debug.Log(error.GenerateErrorReport()); | |
}); | |
} | |
public void TestScript(string scriptName) | |
{ | |
if (!IsLoggedIn) | |
return; | |
ExecuteCloudScriptRequest request = new ExecuteCloudScriptRequest() | |
{ | |
FunctionName = scriptName, | |
FunctionParameter = new Dictionary<string, object> { | |
{ "Smash", 0}, | |
{ "Till", 0}, | |
{ "You", 0}, | |
{ "Crash", Random.Range(3,100)}, // This is to confuse | |
}, | |
RevisionSelection = CloudScriptRevisionOption.Specific, | |
SpecificRevision = Constants.CLOUD_SCRIPT_VER, | |
GeneratePlayStreamEvent = true | |
}; | |
PlayFabClientAPI.ExecuteCloudScript(request, (result) => | |
{ | |
Debug.Log("Test Script called: " + scriptName); | |
}, (PlayFabError error) => | |
{ | |
Debug.Log(error.GenerateErrorReport()); | |
}); | |
} | |
public void FixNegativeCurrencyWithScript(int coins, int gems, int trophy) | |
{ | |
if (!IsLoggedIn) | |
return; | |
ExecuteCloudScriptRequest request = new ExecuteCloudScriptRequest() | |
{ | |
FunctionName = Constants.FUN_NegCurr, | |
FunctionParameter = new Dictionary<string, object> { | |
{ "Smash", coins}, | |
{ "Till", gems}, | |
{ "You", trophy}, | |
{ "Crash", Random.Range(3,100)}, // This is to confuse | |
}, | |
RevisionSelection = CloudScriptRevisionOption.Specific, | |
SpecificRevision = Constants.CLOUD_SCRIPT_VER, | |
GeneratePlayStreamEvent = true | |
}; | |
PlayFabClientAPI.ExecuteCloudScript(request, (result) => | |
{ | |
Debug.Log("Player Stats updated"); | |
GetUserCombinedData(true); | |
}, (PlayFabError error) => | |
{ | |
Debug.Log(error.GenerateErrorReport()); | |
}); | |
} | |
public void GetUpdatedLeaderboard() | |
{ | |
GetAllTimeHighScoreLB(); | |
GetWeeklySmashScoreLB(); | |
} | |
// public void GetGlobalScoreLB() | |
// { | |
// if(!IsLoggedIn) | |
// return; | |
// | |
// GetLeaderboardAroundPlayerRequest LbReq = new GetLeaderboardAroundPlayerRequest() | |
// { | |
// PlayFabId = PF_playFabID, | |
// StatisticName = Constants.RecordSmashScoreLB, | |
// MaxResultsCount = 5 | |
// }; | |
// | |
// PlayFabClientAPI.GetLeaderboardAroundPlayer(LbReq,(result)=> | |
// { | |
// WeeklySmashScoreLB = result.Leaderboard; | |
// | |
// if(LBDataReceivedEvent != null) | |
// LBDataReceivedEvent(); | |
// | |
// },(PlayFabError error)=> | |
// { | |
// Debug.Log(error.GenerateErrorReport()); | |
// }); | |
// } | |
// public void GetGlobalDistanceLB() | |
// { | |
// if(!IsLoggedIn) | |
// return; | |
// | |
// GetLeaderboardAroundPlayerRequest LbReq = new GetLeaderboardAroundPlayerRequest() | |
// { | |
// PlayFabId = PF_playFabID, | |
// StatisticName = Constants.RecordDistanceLB, | |
// MaxResultsCount = 5 | |
// }; | |
// | |
// PlayFabClientAPI.GetLeaderboardAroundPlayer(LbReq,(result)=> | |
// { | |
// GlobalDistanceLB = result.Leaderboard; | |
// | |
// if(LBDataReceivedEvent != null) | |
// LBDataReceivedEvent(); | |
// | |
// },(PlayFabError error)=> | |
// { | |
// Debug.Log(error.GenerateErrorReport()); | |
// }); | |
// } | |
public void GetAllTimeHighScoreLB() | |
{ | |
if (!IsLoggedIn) | |
return; | |
GetFriendLeaderboardAroundPlayerRequest LbReq = new GetFriendLeaderboardAroundPlayerRequest() | |
{ | |
PlayFabId = PF_playFabID, | |
StatisticName = Constants.HighScore, | |
MaxResultsCount = 10 | |
}; | |
PlayFabClientAPI.GetFriendLeaderboardAroundPlayer(LbReq, (result) => | |
{ | |
AllTimeHighScoreLB = result.Leaderboard; | |
if (LBDataReceivedEvent != null) | |
LBDataReceivedEvent(); | |
}, (PlayFabError error) => | |
{ | |
Debug.Log(error.GenerateErrorReport()); | |
}); | |
} | |
public void GetWeeklySmashScoreLB() | |
{ | |
if (!IsLoggedIn) | |
return; | |
GetLeaderboardAroundPlayerRequest LbReq = new GetLeaderboardAroundPlayerRequest() | |
{ | |
PlayFabId = PF_playFabID, | |
StatisticName = Constants.RecordSmashScoreLB, | |
MaxResultsCount = 10 | |
}; | |
PlayFabClientAPI.GetLeaderboardAroundPlayer(LbReq, (result) => | |
{ | |
WeeklyTopScoreLB = result.Leaderboard; | |
if (LBDataReceivedEvent != null) | |
LBDataReceivedEvent(); | |
}, (PlayFabError error) => | |
{ | |
Debug.Log(error.GenerateErrorReport()); | |
}); | |
} | |
/// | |
public void SaveUserData(Dictionary<string, string> userData) | |
{ | |
if (!IsLoggedIn) | |
return; | |
if (IsSavePlayerDateInProgress) | |
return; | |
UpdateUserDataRequest request = new UpdateUserDataRequest() | |
{ | |
Data = userData | |
}; | |
IsSavePlayerDateInProgress = true; | |
PlayFabClientAPI.UpdateUserData(request, (result) => | |
{ | |
IsSavePlayerDateInProgress = false; | |
InfoPopup.Instance.TogglePurchaseProgress(IsSavePlayerDateInProgress, "", Color.white); | |
if (PlayerDataSavedToCloudEvent != null) | |
PlayerDataSavedToCloudEvent(); | |
}, (PlayFabError error) => | |
{ | |
IsSavePlayerDateInProgress = false; | |
InfoPopup.Instance.TogglePurchaseProgress(IsSavePlayerDateInProgress, "Error saving player data...", Color.red); | |
if (PlayerDataSaveErrorEvent != null) | |
PlayerDataSaveErrorEvent(); | |
}); | |
} | |
// | |
public void AddUserVirtualCurrency(string currencyKey, int addDeltaAmt) | |
{ | |
if (!IsLoggedIn) | |
return; | |
AddUserVirtualCurrencyRequest request = new AddUserVirtualCurrencyRequest | |
{ | |
VirtualCurrency = currencyKey, | |
Amount = addDeltaAmt | |
}; | |
PlayFabClientAPI.AddUserVirtualCurrency(request, (result) => | |
{ | |
if (currencyKey == Constants.GEM_KEY) | |
DBMgr.TotalGems = result.Balance; | |
if (currencyKey == Constants.COIN_KEY) | |
DBMgr.TotalCoins = result.Balance; | |
if (currencyKey == Constants.TROPHY_KEY) | |
DBMgr.TotalTrophy = result.Balance; | |
}, OnPlayFabError, currencyKey); | |
} | |
public void SubstractUserCurrency(string currencyKey, int deltaAmount) | |
{ | |
if (!IsLoggedIn) | |
return; | |
SubtractUserVirtualCurrencyRequest request = new SubtractUserVirtualCurrencyRequest | |
{ | |
VirtualCurrency = currencyKey, | |
Amount = deltaAmount | |
}; | |
PlayFabClientAPI.SubtractUserVirtualCurrency(request, (result) => | |
{ | |
if (currencyKey == Constants.GEM_KEY) | |
DBMgr.TotalGems = result.Balance; | |
if (currencyKey == Constants.COIN_KEY) | |
DBMgr.TotalCoins = result.Balance; | |
if (currencyKey == Constants.TROPHY_KEY) | |
DBMgr.TotalTrophy = result.Balance; | |
}, OnPlayFabError, currencyKey); | |
} | |
public void UpdateVC(DBMgr.CURRENCY curr, int amount, string functName, string reason = "") | |
{ | |
if (!IsLoggedIn) | |
return; | |
ExecuteCloudScriptRequest request = new ExecuteCloudScriptRequest() | |
{ | |
FunctionName = functName, | |
FunctionParameter = new Dictionary<string, object> { | |
{"Yolo", amount}, | |
{"What",DBMgr.GetCurrencyKey(curr)}, | |
{"Why",reason} | |
}, | |
RevisionSelection = CloudScriptRevisionOption.Specific, | |
SpecificRevision = Constants.CLOUD_SCRIPT_VER, | |
GeneratePlayStreamEvent = true | |
}; | |
PlayFabClientAPI.ExecuteCloudScript(request, (result) => | |
{ | |
ExecuteCloudScriptResult exResult = (ExecuteCloudScriptResult)result; | |
Debug.Log("Result: " + exResult.FunctionResult); | |
if (functName == Constants.FUN_AdWatched) | |
{ | |
if (curr == DBMgr.CURRENCY.COIN) | |
InfoPopup.Instance.PunchInfo("Coins +" + amount, Color.yellow, 1.0f); | |
if (curr == DBMgr.CURRENCY.GEM) | |
InfoPopup.Instance.PunchInfo("Gems +" + amount, Color.cyan, 1.0f); | |
} | |
AnalyticsMgr.Instance.LogVCEvent(DBMgr.GetCurrencyKey(curr), amount, reason); | |
GetUserCombinedData(true); | |
}, (PlayFabError error) => | |
{ | |
Debug.Log(error.GenerateErrorReport()); | |
}); | |
} | |
public void ValidateGoogleIAP(PurchaseEventArgs e) | |
{ | |
if (!IsLoggedIn) | |
return; | |
DBMgr.Log(">> About to Validate IAP purchase: " + e.purchasedProduct.definition.id); | |
var wrapper = (Dictionary<string, object>)Json.Deserialize(e.purchasedProduct.receipt); | |
if (wrapper == null) | |
return; | |
var store = (string)wrapper["Store"]; | |
var payload = (string)wrapper["Payload"]; | |
var gpDetails = (Dictionary<string, object>)Json.Deserialize(payload); | |
var gpJson = (string)gpDetails["json"]; | |
var gpSig = (string)gpDetails["signature"]; | |
ValidateGooglePlayPurchaseRequest request = new ValidateGooglePlayPurchaseRequest() | |
{ | |
ReceiptJson = gpJson, | |
Signature = gpSig, | |
CurrencyCode = e.purchasedProduct.metadata.isoCurrencyCode, | |
PurchasePrice = decimal.ToUInt32(e.purchasedProduct.metadata.localizedPrice) | |
}; | |
PlayFabClientAPI.ValidateGooglePlayPurchase(request, (result) => | |
{ | |
GetUserCombinedData(true); | |
}, (PlayFabError error) => | |
{ | |
OnValidateIAPError(error, "Google IAP"); | |
}); | |
} | |
public void ValidateAppleIAP(PurchaseEventArgs e) | |
{ | |
if (IsPurchaseItemInProgress) | |
{ | |
InfoPopup.Instance.ShowMessage("Purchase already in Progress", 2.0f, 1.0f, Color.red, false); | |
SoundManager.Instance.PlaySfx("Click_Electronic_16"); | |
return; | |
} | |
IsPurchaseItemInProgress = true; | |
InfoPopup.Instance.TogglePurchaseProgress(IsPurchaseItemInProgress, "Validating Recipt", Color.white); | |
var wrapper = (Dictionary<string, object>)Json.Deserialize(e.purchasedProduct.receipt); | |
if (wrapper == null) | |
return; | |
var store = (string)wrapper["Store"]; | |
var payload = (string)wrapper["Payload"]; | |
ValidateIOSReceiptRequest request = new ValidateIOSReceiptRequest() | |
{ | |
ReceiptData = payload, | |
CurrencyCode = e.purchasedProduct.metadata.isoCurrencyCode, | |
PurchasePrice = decimal.ToInt32(e.purchasedProduct.metadata.localizedPrice) | |
}; | |
PlayFabClientAPI.ValidateIOSReceipt(request, (result) => | |
{ | |
IsPurchaseItemInProgress = false; | |
InfoPopup.Instance.TogglePurchaseProgress(IsPurchaseItemInProgress, "Recipt Validation Success", Color.yellow | |
); | |
GetUserCombinedData(true); | |
}, (PlayFabError error) => | |
{ | |
IsPurchaseItemInProgress = false; | |
InfoPopup.Instance.TogglePurchaseProgress(IsPurchaseItemInProgress, "Recipt Validation Failed", Color.red); | |
OnValidateIAPError(error, "Apple IAP"); | |
}); | |
} | |
public void ValidateAmazonIAP(PurchaseEventArgs e) | |
{ | |
ValidateAmazonReceiptRequest request = new ValidateAmazonReceiptRequest() | |
{ | |
ReceiptId = e.purchasedProduct.receipt, | |
UserId = e.purchasedProduct.definition.storeSpecificId, //Need to change | |
CurrencyCode = e.purchasedProduct.metadata.isoCurrencyCode, | |
PurchasePrice = decimal.ToInt32(e.purchasedProduct.metadata.localizedPrice) | |
}; | |
PlayFabClientAPI.ValidateAmazonIAPReceipt(request, (result) => | |
{ | |
GetUserCombinedData(true); | |
}, (PlayFabError error) => | |
{ | |
OnValidateIAPError(error, "Amazon IAP"); | |
}); | |
} | |
public void OnLoginWithEmailBtn(string userName, string pwd) | |
{ | |
var loginRequest = new LoginWithPlayFabRequest() | |
{ | |
TitleId = PF_TitleId, | |
Username = userName, | |
Password = pwd | |
}; | |
PlayFabClientAPI.LoginWithPlayFab(loginRequest, (result) => | |
{ | |
PF_playFabID = result.PlayFabId; | |
DBMgr.Instance.SaveData(); | |
//LetsFetchData | |
GetUserCombinedData(true, true, true, true, true, true, true); | |
}, OnPlayFabError); | |
} | |
public void OnLinkOrLoginWithFBAccount(string fbAccessTokenStr) | |
{ | |
if (PFMgr.IsLoggedIn && PF_AuthType != AUTH_TYPE.LOGIN_FACEBOOK) | |
{ | |
//Most probably this is a anaymous user | |
var fbLinkRequest = new LinkFacebookAccountRequest() | |
{ | |
AccessToken = fbAccessTokenStr, | |
ForceLink = false | |
}; | |
PlayFabClientAPI.LinkFacebookAccount(fbLinkRequest, (result) => | |
{ | |
if (FBLinkAccountSuccessEvent != null) | |
FBLinkAccountSuccessEvent(); | |
PF_AuthType = PFMgr.AUTH_TYPE.LOGIN_FACEBOOK; | |
DBMgr.Instance.SaveData(); | |
}, OnFBLoginError); | |
} | |
else | |
{ | |
var fbLoginRequest = new LoginWithFacebookRequest() | |
{ | |
TitleId = PFMgr.PF_TitleId, | |
AccessToken = fbAccessTokenStr, | |
CreateAccount = true | |
}; | |
PlayFabClientAPI.LoginWithFacebook(fbLoginRequest, (result) => | |
{ | |
OnLoginSuccess(result); | |
PF_AuthType = PFMgr.AUTH_TYPE.LOGIN_FACEBOOK; | |
DBMgr.Instance.SaveData(); | |
}, OnFBLoginError); | |
} | |
} | |
public void UnLinkFBAccount() | |
{ | |
var request = new UnlinkFacebookAccountRequest() | |
{ | |
}; | |
PlayFabClientAPI.UnlinkFacebookAccount(request, (result) => | |
{ | |
}, OnPlayFabError); | |
} | |
public void OnGameCenterLink() | |
{ | |
var gcLinkRequest = new LinkGameCenterAccountRequest() | |
{ | |
GameCenterId = "" | |
}; | |
PlayFabClientAPI.LinkGameCenterAccount(gcLinkRequest, (result) => | |
{ | |
}, OnPlayFabError); | |
} | |
///Login woth Facebook | |
public void OnLoginWithFacebook() | |
{ | |
//Need to Aquire Facebook Toke here | |
var fbLoginRequest = new LoginWithFacebookRequest() | |
{ | |
TitleId = PF_TitleId, | |
AccessToken = "", | |
CreateAccount = true | |
}; | |
PlayFabClientAPI.LoginWithFacebook(fbLoginRequest, (result) => | |
{ | |
}, OnPlayFabError); | |
} | |
public void GetPlayerStats() | |
{ | |
if (!IsLoggedIn) | |
return; | |
} | |
public void UpdatePlayerStats(List<StatisticUpdate> stats) | |
{ | |
if (!IsLoggedIn) | |
return; | |
UpdatePlayerStatisticsRequest statsrequest = new UpdatePlayerStatisticsRequest() | |
{ | |
Statistics = stats | |
}; | |
PlayFabClientAPI.UpdatePlayerStatistics(statsrequest, (result) => | |
{ | |
}, OnPlayFabError); | |
} | |
public void OnAddUserNamePassword(string userName, string email, string password) | |
{ | |
if (!IsLoggedIn) | |
return; | |
if (string.IsNullOrEmpty(userName) || string.IsNullOrEmpty(email) || string.IsNullOrEmpty(password)) | |
{ | |
GameManager.ShowInfo("Invalid Inputs"); | |
return; | |
} | |
AddUsernamePasswordRequest adduserPwdrequest = new AddUsernamePasswordRequest() | |
{ | |
Username = userName, | |
Password = password, | |
Email = email | |
}; | |
PlayFabClientAPI.AddUsernamePassword(adduserPwdrequest, (request) => | |
{ | |
PF_userName = request.Username; | |
DBMgr.Instance.SaveData(); | |
}, OnPlayFabError); | |
} | |
public void OnUpdateUserDisplayName(string displayName) | |
{ | |
if (!IsLoggedIn) | |
return; | |
if (string.IsNullOrEmpty(displayName)) | |
{ | |
GameManager.ShowInfo("Invalid Inputs"); | |
return; | |
} | |
UpdateUserTitleDisplayNameRequest displayNameReq = new UpdateUserTitleDisplayNameRequest() | |
{ | |
DisplayName = displayName | |
}; | |
PlayFabClientAPI.UpdateUserTitleDisplayName(displayNameReq, (request) => | |
{ | |
PF_diplayName = request.DisplayName; | |
DBMgr.Instance.SaveData(); | |
if (UseDataRecievedEvent != null) | |
UseDataRecievedEvent(); | |
}, (PlayFabError error) => | |
{ | |
switch (error.Error) | |
{ | |
case PlayFabErrorCode.UsernameNotAvailable: | |
{ | |
InfoPopup.Instance.ShowMessage("Display name not available. \n Try new name", 1.0f, 2.0f, Color.red); | |
break; | |
} | |
case PlayFabErrorCode.InvalidParams: | |
case PlayFabErrorCode.InsufficientFunds: | |
case PlayFabErrorCode.InvalidPartnerResponse: | |
{ | |
InfoPopup.Instance.ShowMessage("Try again, invalid error", 3.0f, 1.0f, Color.red); | |
break; | |
} | |
default: | |
{ | |
Debug.Log(error.Error); | |
Debug.Log(error.GenerateErrorReport()); | |
break; | |
} | |
} | |
}); | |
} | |
/// <summary> | |
/// Logs the PF event. | |
/// </summary> | |
/// <param name="eventName">Event name.</param> | |
/// <param name="eventBody">Event body.</param> | |
/// <param name="profileSet">If set to <c>true</c> profile set.</param> | |
public void LogPFEvent(string eventName, Dictionary<string, object> eventBody, bool profileSet = false) | |
{ | |
if (!IsLoggedIn || IsLogErrorInProgress) | |
return; | |
WriteClientPlayerEventRequest logEvent = new WriteClientPlayerEventRequest() | |
{ | |
EventName = eventName, | |
Body = eventBody | |
}; | |
IsLogErrorInProgress = true; | |
PlayFabClientAPI.WritePlayerEvent(logEvent, (results) => | |
{ | |
IsLogErrorInProgress = false; | |
}, (PlayFabError error) => | |
{ | |
IsLogErrorInProgress = false; | |
}); | |
} | |
/// <summary> | |
/// Raises the play fab error event. | |
/// </summary> | |
/// <param name="error">Error.</param> | |
void OnPlayFabError(PlayFabError error) | |
{ | |
try | |
{ | |
Debug.Log(error.GenerateErrorReport()); | |
} | |
catch | |
{ | |
} | |
} | |
void OnPurchaseItemError(PlayFabError error, string itemID, string currKey, int price, string storeID) | |
{ | |
switch (error.Error) | |
{ | |
case PlayFabErrorCode.InvalidParams: | |
{ | |
InfoPopup.Instance.ShowMessage("PurchaseIAP FAIL: Invalid Params", 2.0f, 2.0f, Color.red); | |
break; | |
} | |
case PlayFabErrorCode.ItemNotFound: | |
{ | |
InfoPopup.Instance.ShowMessage("PurchaseIAP FAIL: Item not found", 2.0f, 2.0f, Color.red); | |
break; | |
} | |
case PlayFabErrorCode.WrongVirtualCurrency: | |
{ | |
InfoPopup.Instance.ShowMessage("PurchaseIAP FAIL: Invalid Currency", 2.0f, 2.0f, Color.red); | |
break; | |
} | |
case PlayFabErrorCode.WrongPrice: | |
{ | |
InfoPopup.Instance.ShowMessage("PurchaseIAP FAIL: Wrong price", 2.0f, 2.0f, Color.red); | |
break; | |
} | |
case PlayFabErrorCode.InsufficientFunds: | |
{ | |
InfoPopup.Instance.ShowMessage("PurchaseIAP FAIL: Insufficient funds", 2.0f, 2.0f, Color.red); | |
break; | |
} | |
default: | |
{ | |
Debug.Log(error.GenerateErrorReport()); | |
break; | |
} | |
} | |
} | |
void OnValidateIAPError(PlayFabError error, string storeID) | |
{ | |
switch (error.Error) | |
{ | |
case PlayFabErrorCode.InvalidParams: | |
{ | |
InfoPopup.Instance.ShowMessage("PurchaseIAP FAIL: Invalid Params - " + storeID, 5.0f, 5.0f, Color.red); | |
break; | |
} | |
case PlayFabErrorCode.InvalidReceipt: | |
{ | |
InfoPopup.Instance.ShowMessage("PurchaseIAP FAIL: Invalid Recit - " + storeID, 5.0f, 5.0f, Color.red); | |
break; | |
} | |
case PlayFabErrorCode.ReceiptAlreadyUsed: | |
{ | |
InfoPopup.Instance.ShowMessage("PurchaseIAP FAIL: Receipt already used - " + storeID, 5.0f, 5.0f, Color.red); | |
break; | |
} | |
case PlayFabErrorCode.ReceiptCancelled: | |
{ | |
InfoPopup.Instance.ShowMessage("PurchaseIAP FAIL: Receipt Cancelled - " + storeID, 5.0f, 5.0f, Color.red); | |
break; | |
} | |
case PlayFabErrorCode.NoMatchingCatalogItemForReceipt: | |
{ | |
InfoPopup.Instance.ShowMessage("PurchaseIAP FAIL: No matching Catalog Item for Receipt - " + storeID, 5.0f, 5.0f, Color.red); | |
break; | |
} | |
default: | |
{ | |
Debug.Log(error.GenerateErrorReport()); | |
break; | |
} | |
} | |
} | |
void OnDeviceLoginError(PlayFabError error) | |
{ | |
switch (error.Error) | |
{ | |
case PlayFabErrorCode.AccountNotFound: | |
{ | |
//InfoPopup.Instance.ShowMessage("Account Not found",1.0f,1.0f,Color.red); | |
break; | |
} | |
case PlayFabErrorCode.AccountBanned: | |
{ | |
//InfoPopup.Instance.ShowMessage("Account Banned",3.0f,1.0f,Color.red); | |
//StartCoroutine (Constants.DelayAction (3.0f, ()=>{Application.Quit();})); | |
StartCoroutine(Constants.DelayAction(3.0f, () => { AdMgr.Instance.ShowNonRewardVideo(); })); | |
break; | |
} | |
default: | |
{ | |
Debug.Log(error.GenerateErrorReport()); | |
break; | |
} | |
} | |
} | |
void OnFBLoginError(PlayFabError error) | |
{ | |
switch (error.Error) | |
{ | |
case PlayFabErrorCode.InvalidFacebookToken: | |
{ | |
InfoPopup.Instance.PunchInfo("FB Token expired, re connecting now...", Color.red, 2.0f); | |
StartCoroutine(Constants.DelayAction(2.5f, FBMgr.Instance.CallFBLogin)); | |
break; | |
} | |
case PlayFabErrorCode.FacebookAPIError: | |
{ | |
InfoPopup.Instance.ShowMessage("Facebook API Error, Try later", 1.0f, 1.0f, Color.red); | |
break; | |
} | |
case PlayFabErrorCode.AccountNotFound: | |
{ | |
InfoPopup.Instance.ShowMessage("Facebook Account not Found", 1.0f, 1.0f, Color.red); | |
break; | |
} | |
case PlayFabErrorCode.LinkedAccountAlreadyClaimed: | |
{ | |
FB_AuthToken = string.Empty; | |
PF_AuthType = PFMgr.AUTH_TYPE.LOGIN_DEVICE; | |
DBMgr.Instance.SaveData(); | |
InfoPopup.Instance.ShowMessage("FB Account already claimed, by another userID", 3.0f, 1.0f, Color.red); | |
break; | |
} | |
case PlayFabErrorCode.AccountBanned: | |
{ | |
//InfoPopup.Instance.ShowMessage("Account Banned",3.0f,1.0f,Color.red); | |
//StartCoroutine (Constants.DelayAction (3.0f, ()=>{Application.Quit();})); | |
StartCoroutine(Constants.DelayAction(3.0f, () => { AdMgr.Instance.ShowNonRewardVideo(); })); | |
break; | |
} | |
default: | |
{ | |
Debug.Log(error.Error); | |
Debug.Log(error.GenerateErrorReport()); | |
break; | |
} | |
} | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using UnityEngine; | |
using System.Collections; | |
using System.Collections.Generic; | |
using UnityEngine.UI; | |
using SimpleTween; | |
/// <summary> | |
/// The player controller | |
/// </summary> | |
public class PlayerController : MonoBehaviour | |
{ | |
public static PlayerController Instance; | |
public delegate void ShipChanged(); | |
public static event ShipChanged ShipChangedEvent; | |
public enum MobileInputMode | |
{ | |
Touch, | |
Accelerometer | |
} | |
public static PlayerInputActions InputController; | |
//[SerializeField] private VRInput VR_Input; | |
private float tilt = 0.0f; // current tilt angle - Z | |
private float steer = 0.0f; // Tilting will cause Steer | |
private float pitch = 30.0f; // current pitch angle //X- Axis | |
private float height = 10.0f; // pitch will cause height to alter; | |
private float pitchUpAngle = -12.0f; | |
private float pitchDownSpeed = -2.0f; | |
private bool isAccelerating = false; | |
private bool isRepairing = false; | |
private float acceleration = 1.0f; // speed multiplier for speedboosts/slow motion effects | |
private bool gameEnded = false; // have we crashed? | |
private bool gameCrashed = false; // have we crashed? | |
private bool gameStarted = false; | |
private float thrustPer = 1.0f; | |
private float shieldPer = 1.0f; | |
private float distPer = 0.0f; | |
private float dy = 0.0f; | |
private Tween tween; | |
private int smashesThisRace; | |
private int smashScoreThisRace; | |
private int smashFillRate; | |
private int smashMultiplier; | |
//private int smashMultiplierBase; | |
private int gemsThisRace; | |
private int coinsThisRace; | |
private GameObject smashParticles; | |
private float minDeltaX = 0.0f; | |
private float maxDeltaX = 0.0f; | |
private int currShipIndex = 0; | |
private PlayerModel currentShip; | |
[SerializeField] | |
private PlayerModel testDrone; | |
[SerializeField] | |
private GameObject flyerParticle; | |
[SerializeField] | |
private GameObject hiddenDrone; | |
/// <summary> | |
/// Public Data | |
/// </summary> | |
public float thrustLeft = 0; // gained by surfing // Boost | |
public float shieldsLeft = 0; | |
public float steerInput = 0.0f; | |
public float thrustInput = 0.0f; | |
public List<string> wordsThisRace; | |
public float accelerometerSensitivity = 3.0f; | |
[SerializeField] private GameObject blobShadow; | |
public bool isInvincible = false; | |
public float currentSpeed = 45.0f; // current speed of the ship | |
public Light playerLight; | |
//Particles | |
public GameObject[] onCrashParticles; | |
public GameObject hitParticles; | |
public GameObject glassSmashParticles; | |
public GameObject shipChangeParticle; | |
public PlayerModel[] allShips; | |
/// <summary> | |
/// HealperMethods | |
/// </summary> | |
/// <value>The steer.</value> | |
public float Steer { get { return steer; } } | |
public float Height { get { return height; } } | |
public float Speed { get { return gameEnded ? 0.0f : currentSpeed * acceleration; } } | |
private const float k_ExpDampCoef = -20f; // Coefficient used to damp the rotation. | |
public bool GameStarted | |
{ | |
get { return gameStarted; } | |
set { gameStarted = value; } | |
} | |
public bool GameEnded | |
{ | |
get { return gameEnded; } | |
set { gameEnded = value; } | |
} | |
public bool GameCrashed | |
{ | |
get { return gameCrashed; } | |
set { gameCrashed = value; } | |
} | |
public float Acceleration | |
{ | |
get { return acceleration; } | |
set { acceleration = value; } | |
} | |
public int SmashesThisRace | |
{ | |
get { return smashesThisRace; } | |
set { smashesThisRace = value; } | |
} | |
public int SmashFillRate | |
{ | |
get { return smashFillRate; } | |
set { smashFillRate = value; } | |
} | |
public int NumWordsThisRace | |
{ | |
get { return wordsThisRace.Count; } | |
} | |
public int GemsThisRace | |
{ | |
get { return gemsThisRace; } | |
set { gemsThisRace = value; } | |
} | |
public int ShipIndex | |
{ | |
get { return currShipIndex; } | |
set { currShipIndex = value; } | |
} | |
public int CoinThisRace | |
{ | |
get { return coinsThisRace; } | |
set { coinsThisRace = value; } | |
} | |
public int SmashScoreThisRace | |
{ | |
get { return smashScoreThisRace; } | |
set { smashScoreThisRace = value; } | |
} | |
public int SmashMultiplier | |
{ | |
get { return smashMultiplier; } | |
} | |
public PlayerModel Ship { get { return currentShip; } } | |
public float ThrustPer { get { return thrustPer; } } | |
public float ShiledPer { get { return shieldPer; } } | |
public float DistPer { get { return distPer; } } | |
public float HeightPer { get { return height / Ship.MaxHeight; } } | |
void Awake() | |
{ | |
DontDestroyOnLoad(transform.root.gameObject.gameObject); | |
Instance = this; | |
} | |
void OnEnable() | |
{ | |
// See PlayerActions.cs for this setup. | |
InputController = PlayerInputActions.CreateWithDefaultBindings(); | |
PFMgr.UserInventoryUpdatedEvent += UpdateCurrentShipInfo; | |
//LoadBindings(); | |
} | |
void OnDisable() | |
{ | |
// This properly disposes of the action set and unsubscribes it from | |
// update events so that it doesn't do additional processing unnecessarily. | |
InputController.Destroy(); | |
PFMgr.UserInventoryUpdatedEvent -= UpdateCurrentShipInfo; | |
} | |
private void HandleCancel() | |
{ | |
if (GameStarted) | |
GameManager.Instance.TogglePause(); | |
} | |
public void Reset() | |
{ | |
SetShipModel(); | |
if (Ship != null) | |
Ship.Init(); | |
steer = 0.0f; | |
tilt = 0.0f; | |
pitch = 30.0f; | |
acceleration = 1.0f; | |
gameEnded = false; | |
gameCrashed = false; | |
isInvincible = false; | |
height = 10.0f; | |
smashesThisRace = 0; | |
smashScoreThisRace = 0; | |
smashFillRate = 0; | |
gemsThisRace = 0; | |
smashMultiplier = 1; | |
//smashMultiplierBase = 1; | |
isAccelerating = false; | |
isRepairing = false; | |
CoinThisRace = 0; | |
GemsThisRace = 0; | |
GameStarted = false; | |
wordsThisRace = new List<string>(); | |
if (Ship != null) | |
{ | |
thrustLeft = Ship.MaxThrust; | |
currentSpeed = Ship.StartSpeed; | |
} | |
if (flyerParticle != null) | |
flyerParticle.SetActive(false); | |
GameCamera.Instance.ResetCamera(); | |
ResetPlayerRotation(); | |
} | |
public void OnGameStarted() | |
{ | |
Time.timeScale = 1.0f; | |
GameStarted = true; | |
ResetPlayerRotation(); | |
minDeltaX = LevelManager.Instance.CurrentLevel.minDeltaX; | |
maxDeltaX = LevelManager.Instance.CurrentLevel.maxDeltaX; | |
Ship.ToggleModel(true); | |
EnableInvisiblity(2.0f); | |
Acceleration = 0.1f; | |
shieldsLeft = Ship.MaxShield;//startShield ? 1 : 0; | |
SoundManager.Instance.PlayEngine("AlienHive_Simple", 0.01f); | |
SaveCurrentShipModel(); | |
} | |
public void OnGameOver() | |
{ | |
Time.timeScale = 1.0f; | |
Ship.ToggleModel(false); | |
} | |
public void LoadPlayerData() | |
{ | |
foreach (PlayerModel ship in allShips) | |
ship.OnGameStarted(); | |
LoadShipLastShipID(); | |
} | |
public void ShakePlayer(bool onCrash = true) | |
{ | |
iTween.PunchScale(Ship.gameObject, Vector3.one, 1.0f); | |
} | |
public void LoadShipLastShipID() | |
{ | |
ShipIndex = 0; | |
foreach (PlayerModel ship in allShips) | |
{ | |
if (ship != null && ship.itemID != null && DBMgr.lastPlayedShipID != null && DBMgr.lastPlayedShipID != "") | |
{ | |
if (DBMgr.lastPlayedShipID == ship.itemID) | |
{ | |
break; | |
} | |
} | |
ShipIndex += 1; | |
} | |
SetUpShipWithIndex(ShipIndex); | |
} | |
public void SaveCurrentShipModel() | |
{ | |
if (Ship != null && Ship.IsOwned) | |
{ | |
DBMgr.lastPlayedShipID = Ship.itemID; | |
DBMgr.Instance.SaveData(); | |
} | |
} | |
public void UpdateCurrentShipInfo() | |
{ | |
if (Ship != null) | |
Ship.Init(); | |
UpdateAvailability(); | |
} | |
public void UpdateShipIndex(int delta) | |
{ | |
ShipIndex = (int)Mathf.Repeat(ShipIndex + delta, allShips.Length); | |
SetUpShipWithIndex(ShipIndex); | |
ShowSmashParticles(false); | |
} | |
public void SetUpShipWithIndex(int indexID, bool isTrail = false) | |
{ | |
ShipIndex = indexID; | |
SetShipModel(); | |
Ship.Init(); | |
UpdateAvailability(); | |
if (ShipChangedEvent != null) | |
ShipChangedEvent(); | |
} | |
public void UpdateAvailability() | |
{ | |
Ship.ToggleModel(Ship.IsAvailable); | |
if (hiddenDrone != null) | |
{ | |
if (!Ship.IsOwned && !Ship.IsAvailable) | |
iTween.ShakeScale(hiddenDrone.gameObject, new Vector3(.5f, .5f, .5f), 0.5f); | |
hiddenDrone.gameObject.SetActive(!Ship.IsOwned && !Ship.IsAvailable); | |
} | |
if (!Ship.IsAvailable) | |
SoundManager.Instance.PlaySfx("Alarm_Loop_0"); | |
else | |
SoundManager.Instance.PlaySfx("Slide_Soft_00"); | |
iTween.ShakeScale(Ship.gameObject, new Vector3(.15f, .15f, .15f), 0.5f); | |
Ship.UpdateWobble(); | |
} | |
public void SetUpShipWithCurrentIndex() | |
{ | |
if (Ship != null) | |
SetUpShipWithIndex(Ship.IndexID); | |
} | |
public void UpdateShield(int shieldPlus = 1) | |
{ | |
ShowSmashParticles(); | |
} | |
public void UpdateSmashed(int smashScore, bool enableInvinsible = true) | |
{ | |
AwardCoin(5); | |
smashesThisRace += 1; | |
smashFillRate = (smashesThisRace % Ship.SmashMul); | |
if (smashFillRate == 0) | |
{ | |
smashMultiplier += 1;//smashMultiplierBase + 1; | |
MenuSystem.Instance.gameMenu.soloGameInfo.PunchInfo("x" + smashMultiplier, Color.red, 1f); | |
} | |
int scoreThisSmash = smashMultiplier * smashScore; | |
smashScoreThisRace += scoreThisSmash; | |
MenuSystem.Instance.gameMenu.soloGameInfo.PunchInfo("+" + scoreThisSmash, Color.white, 1f); | |
ShowSmashParticles(); | |
} | |
public void RewardForWordFind(string pickupWord) | |
{ | |
AwardCoin(GameManager.Instance.coinsRewardPerWord); | |
WordChecker.Instance.PunchInfo(pickupWord + "\n" + "Coins +" + GameManager.Instance.coinsRewardPerWord, Color.yellow, 1.5f); | |
wordsThisRace.Add(pickupWord); | |
} | |
public void AwardGems(int gems) | |
{ | |
gemsThisRace += gems; | |
} | |
public void AwardCoin(int coin) | |
{ | |
coin = GameManager.Instance.coinpickMul * coin; | |
coinsThisRace += coin; | |
MenuSystem.Instance.gameMenu.soloGameInfo.PunchCoinPickup(); | |
} | |
public void UpdateThrust(float thrustAmount, bool maxFill = false) | |
{ | |
if (!maxFill) | |
thrustLeft = Mathf.Clamp(thrustLeft + thrustAmount, 0, currentShip.MaxThrust); | |
else | |
thrustLeft = currentShip.MaxThrust; | |
} | |
public void ResetPlayerRotation() | |
{ | |
transform.localEulerAngles = new Vector3(0.0f, 0.0f, 0.0f); | |
transform.localPosition = new Vector3(0.0f, LevelManager.Instance.CurrentLevel.MinHeight, 4.0f); | |
if (Ship != null) | |
{ | |
Ship.transform.eulerAngles = new Vector3(-pitchUpAngle, 0.0f, 0.0f); | |
Ship.transform.localPosition = Vector3.zero; | |
} | |
} | |
void SetShipModel() | |
{ | |
// destroy the current model if it exists | |
if (currentShip != null) | |
{ | |
DestroyImmediate(currentShip.gameObject); | |
} | |
PlayerModel nextModel = null; | |
foreach (PlayerModel model in allShips) | |
{ | |
if (model.IndexID == ShipIndex) | |
{ | |
nextModel = model; | |
break; | |
} | |
} | |
currentShip = Instantiate(nextModel, transform.position, transform.rotation) as PlayerModel; | |
Ship.transform.parent = transform; | |
Color currentFog = RenderSettings.fogColor; | |
Color currAmbColor = RenderSettings.ambientLight; | |
} | |
private float GetSteerInput() | |
{ | |
if (!GameCamera.VRModeEnabled && !DBMgr.tiltEnabled) | |
{ | |
if (InputController.Left.IsPressed || (Input.touchCount == 1 && (Input.GetTouch(0).position.x < (0.5f * Screen.width)))) | |
return -1.0f; | |
else if (InputController.Right.IsPressed || (Input.touchCount == 1 && (Input.GetTouch(0).position.x > (0.5f * Screen.width)))) | |
return 1.0f; | |
else | |
return 0.0f; | |
} | |
else | |
{ | |
// Use the orientation of the device as the steering value | |
return accelerometerSensitivity * Input.acceleration.x; | |
} | |
} | |
private float GetPitchInput() | |
{ | |
if (Input.touchCount == 0) | |
return Input.GetAxis("Vertical"); | |
else if (InputController.Up.IsPressed || Input.touchCount == ((GameCamera.VRModeEnabled || DBMgr.tiltEnabled) ? 1 : 2)) | |
return 1.0f; | |
else | |
return -1.0f; | |
// | |
// if(Input.touchCount == 0) | |
// return Input.GetAxis("Vertical"); | |
// if(Input.touchCount == (GameCamera.VRModeEnabled ? 1: 2)) | |
// return 1.0f; | |
// else | |
// return -1.0f; | |
} | |
void Update() | |
{ | |
if (currentShip == null) | |
return; | |
if (GameManager.Instance != null && GameManager.currGameState == GameManager.GameState.InMenus) | |
Ship.InMenuRotate(); | |
if (!GameStarted) | |
return; | |
UpdateShipStats(); | |
} | |
//These are the | |
void FixedUpdate() | |
{ | |
if (!GameStarted || GameEnded || GameManager.IsPaused) | |
return; | |
if (currentShip == null) | |
return; | |
UpdatePitchAndHeight(); | |
UpdateSteerTiltDrift(); | |
} | |
public void UpdateShipStats() | |
{ | |
thrustPer = thrustLeft / Ship.MaxThrust; | |
shieldPer = shieldsLeft / Ship.MaxShield; | |
//TODO: Need to move DBMgr.recordDist out of calling every frame | |
//distPer = LevelManager.Instance.DistanceThisRace/DBMgr.RecordDistance; | |
MenuSystem.Instance.gameMenu.soloGameInfo.UpdateStats(); | |
} | |
public void PlayerCrashed(PlayerBlocker blocker) | |
{ | |
shieldsLeft -= 1; | |
MenuSystem.Instance.gameMenu.soloGameInfo.PulseShieldCont(); | |
WordChecker.Instance.PunchInfo("Hit .. ", Color.red, 1.0f); | |
if (shieldsLeft > 0) | |
{ | |
ShakePlayer(); | |
Ship.ShatterGlass(); | |
//ShowSmashParticles(); | |
ShowHitParticle(); | |
EnableInvisiblity(); | |
Destroy(blocker.gameObject, 0.5f); | |
isRepairing = true; | |
iTween.ValueTo(gameObject, iTween.Hash("from", 0.0f, "to", 1.0f, "onUpdate", "RepairComplete", "time", 1.0f)); | |
//Reset SmashMultiplier to 1 | |
// smashMultiplier = 1; | |
// SmashFillRate = 0; | |
} | |
else | |
{ | |
WordChecker.Instance.PunchInfo("CRASHED !", Color.cyan, 1.0f); | |
bool shouldOfferMulligan = (GameManager.Instance.mulligansUsed < ((int)GameManager.Instance.gameDifficulty) + 1); | |
if (shouldOfferMulligan) | |
{ | |
//OfferMulligan | |
//NOTE: we ae not using co-routiens, as they seem to be casuing some timing issues | |
CrashOccured(false); | |
InfoPopup.Instance.ShowMessage("Crashed", 1.5f, 0.25f, Color.white); | |
iTween.ValueTo(gameObject, iTween.Hash("from", 0.0f, "to", 1.0f, "onUpdate", "OfferMulligan", "time", 1.0f)); | |
Destroy(blocker.gameObject, 0.5f); | |
} | |
else | |
{ | |
CrashOccured(true); | |
InfoPopup.Instance.ShowMessage("You are Finished!", 1.5f, 0.25f, Color.red); | |
Destroy(blocker.gameObject, 0.5f); | |
} | |
} | |
} | |
void OfferMulligan(float val) { if (val >= 1.0f) { MenuSystem.Instance.gameMenu.OfferMulligan(); } } | |
void CallOnGameOver(float val) { if (val >= 1.0f) { GameManager.Instance.OnGameOver(); } } | |
void RepairComplete(float val) { if (val >= 1.0f) { isRepairing = false; } } | |
public void CrashOccured(bool endGame = true) | |
{ | |
Ship.ShatterGlass(); | |
// come to a complete stop and hide the player model | |
gameEnded = endGame; | |
gameCrashed = true; | |
if (gameEnded) | |
{ | |
Ship.ToggleModel(false); | |
iTween.ValueTo(gameObject, iTween.Hash("from", 0.0f, "to", 1.0f, "onUpdate", "CallOnGameOver", "time", 1.5f)); | |
SoundManager.Instance.StopEngine(); | |
ShowExplosionOnCrash(); | |
} | |
else | |
{ | |
GameManager.currGameState = GameManager.GameState.Mulligan; | |
} | |
///Shake Ship & Camers | |
ShakePlayer(); | |
ShowHitParticle(); | |
ShowSmashParticles(); | |
} | |
public void RespawnPlayer() | |
{ | |
gameEnded = false; | |
gameCrashed = false; | |
steer = 0.0f; | |
acceleration = 0.1f; | |
currentSpeed = Ship.StartSpeed; | |
thrustLeft = Ship.MaxThrust; | |
shieldsLeft = 0; | |
Time.timeScale = 1.0f; | |
GameManager.Instance.ResumeGame(); | |
EnableInvisiblity(DBMgr._mulliganRespawnDelay); | |
} | |
void EnableInvisiblity(float disableTime = 0.25f) | |
{ | |
isInvincible = true; | |
iTween.ValueTo(gameObject, iTween.Hash("from", 0.0f, "to", 1.0f, "onUpdate", "DisableInvisiblity", "time", disableTime)); | |
} | |
void DisableInvisiblity(float val) | |
{ | |
if (val >= 1.0f) | |
isInvincible = false; | |
} | |
void UpdateSteerTiltDrift() | |
{ | |
// get the steering input | |
Vector3 playerRot = Ship.transform.eulerAngles; | |
Vector3 playerPos = transform.localPosition; | |
steerInput = GetSteerInput(); | |
//Manage Tilt & Camera Drifting | |
float tiltSpeedDelta = Ship.TiltSpeed * Time.deltaTime; | |
float targetTilt = -steerInput * Ship.TiltAngle; | |
tilt = Mathf.Lerp(tilt, targetTilt, tiltSpeedDelta); | |
playerRot.z = tilt; | |
Ship.transform.eulerAngles = playerRot; | |
//Manage Steering - Moving the Ship Left & Right | |
float steerBuildUp = Mathf.Clamp(Mathf.Abs(tilt) * Ship.SteerBuildUp, 1.0f, 20.0f); | |
float steerSpd = Ship.SteerSpeed * (Mathf.Lerp(acceleration, steerBuildUp, 0.5f)); | |
float steerSpeedDelta = Ship.SteerSpeed * Time.deltaTime; | |
steer = Mathf.Lerp(steer, steerSpd * steerInput, steerSpeedDelta); | |
//playerRot.y = (steer * 0.25f); | |
float xDelta = steer * Time.deltaTime; | |
playerPos.x = Mathf.Clamp(playerPos.x + xDelta, minDeltaX, maxDeltaX); | |
transform.localPosition = playerPos; | |
//Update the Camera | |
GameCamera.Instance.OnPlayerSteerUpdate(steerInput * 0.01f, playerPos.x); | |
if (!isAccelerating) | |
{ | |
UpdateThrust(Ship.ThrustFillRate); | |
} | |
} | |
void UpdatePitchAndHeight() | |
{ | |
Vector3 playerPos = transform.localPosition; | |
Vector3 playerRot = Ship.transform.eulerAngles; | |
// smoothly lerp our current pitch value towards the target input value | |
float pitchSpeedDelta = Ship.PitchUpSpeed * Time.deltaTime; | |
thrustInput = GetPitchInput(); | |
thrustInput = thrustInput <= 0 ? -1.0f : thrustInput; | |
thrustInput = (thrustLeft <= 0 || thrustInput <= 0) ? pitchDownSpeed : thrustInput; | |
float pitchSpeed = Ship.PitchUpSpeed * (Mathf.Lerp(acceleration, 1.0f, 0.5f)); | |
pitch = Mathf.Lerp(pitch, pitchSpeed * thrustInput, pitchSpeedDelta); | |
// pitch the vehicle as we pitch | |
float targetPitch = thrustInput * pitch; | |
targetPitch = (thrustInput > 0) ? (targetPitch - pitchUpAngle) : targetPitch; | |
pitch = Mathf.Lerp(pitch, targetPitch, pitchSpeedDelta); | |
if (isRepairing) | |
{ | |
isAccelerating = false; | |
acceleration = 0.75f; | |
} | |
else | |
{ | |
if (thrustInput > 0 && thrustPer > 0.05f) | |
{ | |
UpdateThrust(-Ship.ThrustBurnRate * Height); | |
acceleration = Mathf.Lerp(acceleration, Ship.Acceleration, 1.0f); | |
isAccelerating = true; | |
} | |
else | |
{ | |
acceleration = Mathf.Lerp(acceleration, 1.0f, 0.5f); | |
isAccelerating = false; | |
} | |
} | |
if (flyerParticle != null) | |
flyerParticle.gameObject.SetActive(GameStarted); | |
//Apply the Pitch to the height of the player | |
float targetHeight = height + (thrustInput * pitchSpeedDelta * 2.0f); | |
height = Mathf.Clamp(targetHeight, LevelManager.Instance.CurrentLevel.MinHeight, Ship.MaxHeight); | |
float soundVal = height / Ship.MaxHeight; | |
float volumeDelta = 1.0f - soundVal; | |
SoundManager.Instance.UpdateEngineVolume(volumeDelta); | |
SoundManager.Instance.UpdateAmbientVolume(soundVal); | |
//Position updates | |
dy = (dy + Time.deltaTime) % (2 * Mathf.PI); | |
if (thrustInput < 0) | |
playerPos.y = height + (Mathf.Sin(dy) * 0.01f); | |
else | |
playerPos.y = height; | |
playerPos.z = Mathf.Lerp(playerPos.z, DBMgr.Instance.PlayerZoomLevel, 2.5f); | |
transform.localPosition = playerPos; | |
//Rotation updates | |
playerRot.x = -pitch; | |
Ship.transform.eulerAngles = playerRot; | |
GameCamera.Instance.OnPlayerPitchUpdate(height); | |
if (blobShadow != null && Ship != null) | |
{ | |
float heightPerMax = ((height + Ship.gameObject.transform.localPosition.y) / Ship.MaxHeight); | |
float heightPer = 1.0f - heightPerMax; | |
float locScale = 2.0f * heightPer; | |
blobShadow.transform.localScale = new Vector3(locScale, locScale, locScale); | |
} | |
} | |
public void GetPlayerReady() | |
{ | |
Vector3 playerPos = transform.localPosition; | |
playerPos.z = Mathf.Lerp(playerPos.z, -DBMgr.Instance.PlayerZoomLevel, 2.5f); | |
transform.localPosition = playerPos; | |
} | |
public void ShowHitParticle() | |
{ | |
GameObject particles = Instantiate(hitParticles, transform.position, Quaternion.identity) as GameObject; | |
particles.gameObject.transform.parent = gameObject.transform; | |
Destroy(particles, 2.0f); | |
SoundManager.Instance.PlayRandomOnChannel(SoundManager.Instance.hitSounds, SoundManager.Instance.sfxChannel); | |
} | |
public void ShowExplosionOnCrash() | |
{ | |
SoundManager.Instance.PlaySfx("Explosion"); | |
foreach (GameObject crashParticle in onCrashParticles) | |
{ | |
if (crashParticle != null) | |
{ | |
GameObject explosion = Instantiate(crashParticle, transform.position, Quaternion.identity) as GameObject; | |
explosion.gameObject.transform.parent = gameObject.transform; | |
Destroy(explosion, 5.0f); | |
} | |
} | |
} | |
public void ShowSmashParticles(bool playSound = true) | |
{ | |
if (glassSmashParticles != null && smashParticles == null) | |
{ | |
smashParticles = Instantiate(glassSmashParticles, transform.position, Quaternion.identity) as GameObject; | |
smashParticles.transform.parent = transform; | |
Destroy(smashParticles, 1.0f); | |
} | |
} | |
public void ShowShipUpgradeParticles(float killTime = 3.0f) | |
{ | |
if (shipChangeParticle != null) | |
{ | |
iTween.PunchScale(Ship.gameObject, Vector3.one, 1.0f); | |
GameObject particles = Instantiate(shipChangeParticle, new Vector3(transform.position.x, transform.position.y - 1.0f, transform.position.z), Ship.transform.rotation) as GameObject; | |
particles.gameObject.transform.parent = gameObject.transform; | |
particles.transform.parent = transform; | |
Destroy(particles, killTime); | |
SoundManager.Instance.PlaySfx("SlowDown"); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment