Reformat code

This commit is contained in:
Lncvrt committed 2026-02-21 13:34:45 -07:00
1 parent d0946d1e39
commit e8cf9bc523
77 files changed
+1041 -2187

No files matched your search

@@ -4,16 +4,14 @@ using UnityEngine;
using UnityEngine.Networking;
using UnityEngine.UI;
public class AccountChangePassword : MonoBehaviour
{
public class AccountChangePassword : MonoBehaviour {
[SerializeField] private TMP_Text changePasswordStatusText;
[SerializeField] private TMP_InputField changePasswordNewPasswordInput;
[SerializeField] private TMP_InputField changePasswordRetypeNewPasswordInput;
[SerializeField] private Button changePasswordBackButton;
[SerializeField] private Button changePasswordSubmitButton;
void Awake()
{
void Awake() {
changePasswordNewPasswordInput.onSelect.AddListener((_) => changePasswordNewPasswordInput.caretPosition = changePasswordNewPasswordInput.text.Length);
changePasswordRetypeNewPasswordInput.onSelect.AddListener((_) => changePasswordRetypeNewPasswordInput.caretPosition = changePasswordRetypeNewPasswordInput.text.Length);
@@ -21,17 +19,14 @@ public class AccountChangePassword : MonoBehaviour
changePasswordSubmitButton.onClick.AddListener(() => ChangePassword());
}
void OnEnable()
{
void OnEnable() {
changePasswordNewPasswordInput.text = "";
changePasswordRetypeNewPasswordInput.text = "";
changePasswordStatusText.text = "";
}
async void ChangePassword()
{
if (changePasswordNewPasswordInput.text != changePasswordRetypeNewPasswordInput.text)
{
async void ChangePassword() {
if (changePasswordNewPasswordInput.text != changePasswordRetypeNewPasswordInput.text) {
Tools.UpdateStatusText(changePasswordStatusText, "Passwords do not match", Color.red);
return;
}
@@ -45,22 +40,18 @@ public class AccountChangePassword : MonoBehaviour
request.SetRequestHeader("ClientVersion", Application.version);
request.SetRequestHeader("ClientPlatform", Application.platform.ToString());
await request.SendWebRequest();
if (request.downloadHandler.text == null)
{
if (request.downloadHandler.text == null) {
changePasswordBackButton.interactable = true;
changePasswordSubmitButton.interactable = true;
Tools.UpdateStatusText(changePasswordStatusText, "Failed to make HTTP request", Color.red);
return;
}
var jsonResponse = JObject.Parse(request.downloadHandler.text);
if ((bool)jsonResponse["success"])
{
if ((bool)jsonResponse["success"]) {
BazookaManager.Instance.SetAccountSession((string)jsonResponse["data"]);
AccountHandler.instance.SwitchPanel(0);
Tools.UpdateStatusText(AccountHandler.instance.accountLoggedIn.loggedInText, "Password changed successfully", Color.green);
}
else
{
} else {
Tools.UpdateStatusText(changePasswordStatusText, (string)jsonResponse["message"], Color.red);
}
changePasswordBackButton.interactable = true;
@@ -4,29 +4,25 @@ using UnityEngine;
using UnityEngine.Networking;
using UnityEngine.UI;
public class AccountChangeUsername : MonoBehaviour
{
public class AccountChangeUsername : MonoBehaviour {
[SerializeField] private TMP_Text changeUsernameStatusText;
[SerializeField] private TMP_InputField changeUsernameNewUsernameInput;
[SerializeField] private Button changeUsernameBackButton;
[SerializeField] private Button changeUsernameSubmitButton;
void Awake()
{
void Awake() {
changeUsernameNewUsernameInput.onSelect.AddListener((_) => changeUsernameNewUsernameInput.caretPosition = changeUsernameNewUsernameInput.text.Length);
changeUsernameBackButton.onClick.AddListener(() => AccountHandler.instance.SwitchPanel(0));
changeUsernameSubmitButton.onClick.AddListener(() => ChangeUsername());
}
void OnEnable()
{
void OnEnable() {
changeUsernameNewUsernameInput.text = "";
changeUsernameStatusText.text = "";
}
async void ChangeUsername()
{
async void ChangeUsername() {
changeUsernameBackButton.interactable = false;
changeUsernameSubmitButton.interactable = false;
WWWForm dataForm = new();
@@ -37,23 +33,19 @@ public class AccountChangeUsername : MonoBehaviour
request.SetRequestHeader("ClientVersion", Application.version);
request.SetRequestHeader("ClientPlatform", Application.platform.ToString());
await request.SendWebRequest();
if (request.downloadHandler.text == null)
{
if (request.downloadHandler.text == null) {
changeUsernameBackButton.interactable = true;
changeUsernameSubmitButton.interactable = true;
Tools.UpdateStatusText(changeUsernameStatusText, "Failed to make HTTP request", Color.red);
return;
}
var jsonResponse = JObject.Parse(request.downloadHandler.text);
if ((bool)jsonResponse["success"])
{
if ((bool)jsonResponse["success"]) {
BazookaManager.Instance.SetAccountName(changeUsernameNewUsernameInput.text);
BazookaManager.Instance.SetAccountSession((string)jsonResponse["data"]);
AccountHandler.instance.SwitchPanel(0);
Tools.UpdateStatusText(AccountHandler.instance.accountLoggedIn.loggedInText, "Username changed successfully", Color.green);
}
else
{
} else {
Tools.UpdateStatusText(changeUsernameStatusText, (string)jsonResponse["message"], Color.red);
}
changeUsernameBackButton.interactable = true;
@@ -4,8 +4,7 @@ using UnityEngine;
using UnityEngine.Networking;
using UnityEngine.UI;
public class AccountForgotDetails : MonoBehaviour
{
public class AccountForgotDetails : MonoBehaviour {
[SerializeField] internal TMP_Text forgotDetailsTitleText;
[SerializeField] private TMP_Text forgotDetailsStatusText;
[SerializeField] private TMP_InputField forgotDetailsEmailInput;
@@ -14,13 +13,11 @@ public class AccountForgotDetails : MonoBehaviour
[SerializeField] internal Button forgotDetailsSubmitButton;
internal int mode = 0;
void Awake()
{
void Awake() {
forgotDetailsEmailInput.onSelect.AddListener((_) => forgotDetailsEmailInput.caretPosition = forgotDetailsEmailInput.text.Length);
forgotDetailsVerifyCodeInput.onSelect.AddListener((_) => forgotDetailsVerifyCodeInput.caretPosition = forgotDetailsVerifyCodeInput.text.Length);
forgotDetailsBackButton.onClick.AddListener(() =>
{
forgotDetailsBackButton.onClick.AddListener(() => {
forgotDetailsBackButton.interactable = false;
forgotDetailsSubmitButton.interactable = false;
mode = 0;
@@ -31,14 +28,12 @@ public class AccountForgotDetails : MonoBehaviour
forgotDetailsSubmitButton.onClick.AddListener(() => ForgotDetails());
}
void OnEnable()
{
void OnEnable() {
forgotDetailsEmailInput.text = "";
forgotDetailsVerifyCodeInput.text = "";
}
async void ForgotDetails()
{
async void ForgotDetails() {
forgotDetailsBackButton.interactable = false;
forgotDetailsSubmitButton.interactable = false;
WWWForm dataForm = new();
@@ -50,8 +45,7 @@ public class AccountForgotDetails : MonoBehaviour
request.SetRequestHeader("ClientVersion", Application.version);
request.SetRequestHeader("ClientPlatform", Application.platform.ToString());
await request.SendWebRequest();
if (request.downloadHandler.text == null)
{
if (request.downloadHandler.text == null) {
forgotDetailsBackButton.interactable = true;
forgotDetailsSubmitButton.interactable = true;
Tools.UpdateStatusText(forgotDetailsStatusText, "Failed to make HTTP request", Color.red);
+9 -19
View File
@@ -2,8 +2,7 @@ using UnityEngine;
using UnityEngine.InputSystem;
using UnityEngine.SceneManagement;
public class AccountHandler : MonoBehaviour
{
public class AccountHandler : MonoBehaviour {
public static AccountHandler instance;
public AccountLoggedIn accountLoggedIn;
[SerializeField] private AccountLoggedOut accountLoggedOut;
@@ -14,27 +13,20 @@ public class AccountHandler : MonoBehaviour
[SerializeField] private AccountRefreshLogin accountRefreshLogin;
[SerializeField] internal AccountForgotDetails accountForgotDetails;
void Awake()
{
void Awake() {
instance = this;
}
void Start()
{
if (BazookaManager.Instance.GetAccountID() != null && BazookaManager.Instance.GetAccountName() != null && BazookaManager.Instance.GetAccountSession() != null)
{
void Start() {
if (BazookaManager.Instance.GetAccountID() != null && BazookaManager.Instance.GetAccountName() != null && BazookaManager.Instance.GetAccountSession() != null) {
SwitchPanel(0);
}
else
{
} else {
SwitchPanel(1);
}
}
public void SwitchPanel(int panel)
{
switch (panel)
{
public void SwitchPanel(int panel) {
switch (panel) {
case 0:
accountLoggedIn.gameObject.SetActive(true);
accountLoggedOut.gameObject.SetActive(false);
@@ -119,10 +111,8 @@ public class AccountHandler : MonoBehaviour
foreach (CustomColorObject customColorObject in FindObjectsByType<CustomColorObject>(FindObjectsSortMode.None)) customColorObject.SetColor();
}
async void Update()
{
if (Keyboard.current.escapeKey.wasPressedThisFrame)
{
async void Update() {
if (Keyboard.current.escapeKey.wasPressedThisFrame) {
if (accountChangePassword.gameObject.activeSelf || accountChangeUsername.gameObject.activeSelf || accountRefreshLogin.gameObject.activeSelf) SwitchPanel(0);
else if (accountLogin.gameObject.activeSelf || accountRegister.gameObject.activeSelf) SwitchPanel(1);
else if (accountForgotDetails.gameObject.activeSelf) accountForgotDetails.forgotDetailsBackButton.onClick.Invoke();
+11 -23
View File
@@ -7,8 +7,7 @@ using UnityEngine;
using UnityEngine.Networking;
using UnityEngine.UI;
public class AccountLoggedIn : MonoBehaviour
{
public class AccountLoggedIn : MonoBehaviour {
public TMP_Text loggedInText;
[SerializeField] private AccountLoggedOut accountLoggedOut;
[SerializeField] private Button loggedInChangeUsernameButton;
@@ -19,30 +18,26 @@ public class AccountLoggedIn : MonoBehaviour
[SerializeField] private Button loggedInLogoutButton;
[SerializeField] private Button loggedInBackButton;
void Awake()
{
void Awake() {
loggedInChangeUsernameButton.onClick.AddListener(() => AccountHandler.instance.SwitchPanel(4));
loggedInChangePasswordButton.onClick.AddListener(() => AccountHandler.instance.SwitchPanel(5));
loggedInSaveButton.onClick.AddListener(() => SaveAccount());
loggedInLoadButton.onClick.AddListener(() => LoadAccount());
loggedInRefreshLoginButton.onClick.AddListener(() => AccountHandler.instance.SwitchPanel(6));
loggedInLogoutButton.onClick.AddListener(() =>
{
loggedInLogoutButton.onClick.AddListener(() => {
BazookaManager.Instance.ResetSave();
AccountHandler.instance.SwitchPanel(1);
});
}
void OnEnable()
{
void OnEnable() {
loggedInSaveButton.interactable = true;
loggedInLoadButton.interactable = true;
var textColor = BazookaManager.Instance.GetColorSettingText();
Tools.UpdateStatusText(loggedInText, "Logged in as: " + BazookaManager.Instance.GetAccountName(), new Color(int.Parse(textColor[0].ToString()) / 255f, int.Parse(textColor[1].ToString()) / 255f, int.Parse(textColor[2].ToString()) / 255f));
}
async void SaveAccount()
{
async void SaveAccount() {
loggedInChangeUsernameButton.interactable = false;
loggedInChangePasswordButton.interactable = false;
loggedInSaveButton.interactable = false;
@@ -58,8 +53,7 @@ public class AccountLoggedIn : MonoBehaviour
request.SetRequestHeader("ClientVersion", Application.version);
request.SetRequestHeader("ClientPlatform", Application.platform.ToString());
await request.SendWebRequest();
if (request.downloadHandler.text == null)
{
if (request.downloadHandler.text == null) {
loggedInChangeUsernameButton.interactable = true;
loggedInChangePasswordButton.interactable = true;
loggedInSaveButton.interactable = true;
@@ -81,8 +75,7 @@ public class AccountLoggedIn : MonoBehaviour
loggedInBackButton.interactable = true;
}
async void LoadAccount()
{
async void LoadAccount() {
loggedInChangeUsernameButton.interactable = false;
loggedInChangePasswordButton.interactable = false;
loggedInSaveButton.interactable = false;
@@ -96,8 +89,7 @@ public class AccountLoggedIn : MonoBehaviour
request.SetRequestHeader("ClientVersion", Application.version);
request.SetRequestHeader("ClientPlatform", Application.platform.ToString());
await request.SendWebRequest();
if (request.downloadHandler.text == null)
{
if (request.downloadHandler.text == null) {
loggedInChangeUsernameButton.interactable = true;
loggedInChangePasswordButton.interactable = true;
loggedInSaveButton.interactable = true;
@@ -109,18 +101,14 @@ public class AccountLoggedIn : MonoBehaviour
return;
}
var jsonResponse = JObject.Parse(request.downloadHandler.text);
if ((bool)jsonResponse["success"])
{
if ((bool)jsonResponse["success"]) {
BazookaManager.Instance.saveFile = JObject.FromObject(jsonResponse["data"]);
if (!Application.isMobilePlatform)
{
if (!Application.isMobilePlatform) {
var width = Display.main.systemWidth;
var height = Display.main.systemHeight;
Screen.SetResolution(width, height, BazookaManager.Instance.GetSettingFullScreen());
QualitySettings.vSyncCount = BazookaManager.Instance.GetSettingVsync() ? 1 : -1;
}
else
{
} else {
Application.targetFrameRate = 360;
QualitySettings.vSyncCount = 0;
}
@@ -1,13 +1,11 @@
using UnityEngine;
using UnityEngine.UI;
public class AccountLoggedOut : MonoBehaviour
{
public class AccountLoggedOut : MonoBehaviour {
[SerializeField] private Button loggedOutLoginButton;
[SerializeField] private Button loggedOutRegisterButton;
void Awake()
{
void Awake() {
loggedOutLoginButton.onClick.AddListener(() => AccountHandler.instance.SwitchPanel(2));
loggedOutRegisterButton.onClick.AddListener(() => AccountHandler.instance.SwitchPanel(3));
}
+10 -21
View File
@@ -5,8 +5,7 @@ using UnityEngine;
using UnityEngine.Networking;
using UnityEngine.UI;
public class AccountLogin : MonoBehaviour
{
public class AccountLogin : MonoBehaviour {
[SerializeField] private TMP_Text loginPanelStatusText;
[SerializeField] private TMP_InputField loginUsernameInput;
[SerializeField] private TMP_InputField loginPasswordInput;
@@ -15,23 +14,20 @@ public class AccountLogin : MonoBehaviour
[SerializeField] private Button loginBackButton;
[SerializeField] private Button loginSubmitButton;
void Awake()
{
void Awake() {
loginUsernameInput.onSelect.AddListener((_) => loginUsernameInput.caretPosition = loginUsernameInput.text.Length);
loginPasswordInput.onSelect.AddListener((_) => loginPasswordInput.caretPosition = loginPasswordInput.text.Length);
loginBackButton.onClick.AddListener(() => AccountHandler.instance.SwitchPanel(1));
loginSubmitButton.onClick.AddListener(() => SubmitLogin());
forgotUsernameButton.onClick.AddListener(() =>
{
forgotUsernameButton.onClick.AddListener(() => {
AccountHandler.instance.SwitchPanel(7);
AccountHandler.instance.accountForgotDetails.mode = 0;
AccountHandler.instance.accountForgotDetails.forgotDetailsTitleText.text = "Forgot username";
AccountHandler.instance.accountForgotDetails.forgotDetailsBackButton.interactable = true;
AccountHandler.instance.accountForgotDetails.forgotDetailsSubmitButton.interactable = true;
});
forgotPasswordButton.onClick.AddListener(() =>
{
forgotPasswordButton.onClick.AddListener(() => {
AccountHandler.instance.SwitchPanel(7);
AccountHandler.instance.accountForgotDetails.mode = 1;
AccountHandler.instance.accountForgotDetails.forgotDetailsTitleText.text = "Forgot password";
@@ -40,19 +36,16 @@ public class AccountLogin : MonoBehaviour
});
}
void OnEnable()
{
void OnEnable() {
loginUsernameInput.text = "";
loginPasswordInput.text = "";
loginPanelStatusText.text = "";
}
async void SubmitLogin()
{
async void SubmitLogin() {
loginBackButton.interactable = false;
loginSubmitButton.interactable = false;
if (loginUsernameInput.text == string.Empty || loginPasswordInput.text == string.Empty)
{
if (loginUsernameInput.text == string.Empty || loginPasswordInput.text == string.Empty) {
Tools.UpdateStatusText(loginPanelStatusText, "All input fields must be filled", Color.red);
return;
}
@@ -64,24 +57,20 @@ public class AccountLogin : MonoBehaviour
request.SetRequestHeader("ClientVersion", Application.version);
request.SetRequestHeader("ClientPlatform", Application.platform.ToString());
await request.SendWebRequest();
if (request.downloadHandler.text == null)
{
if (request.downloadHandler.text == null) {
loginBackButton.interactable = true;
loginSubmitButton.interactable = true;
Tools.UpdateStatusText(loginPanelStatusText, "Failed to make HTTP request", Color.red);
return;
}
var jsonResponse = JObject.Parse(request.downloadHandler.text);
if ((bool)jsonResponse["success"])
{
if ((bool)jsonResponse["success"]) {
BazookaManager.Instance.SetAccountSession((string)jsonResponse["data"]["session"]);
BazookaManager.Instance.SetAccountName((string)jsonResponse["data"]["username"]);
BazookaManager.Instance.SetAccountID(BigInteger.Parse((string)jsonResponse["data"]["id"]));
AccountHandler.instance.SwitchPanel(0);
Tools.UpdateStatusText(loginPanelStatusText, "", Color.red);
}
else
{
} else {
Tools.UpdateStatusText(loginPanelStatusText, (string)jsonResponse["message"], Color.red);
}
loginBackButton.interactable = true;
@@ -5,16 +5,14 @@ using UnityEngine;
using UnityEngine.Networking;
using UnityEngine.UI;
public class AccountRefreshLogin : MonoBehaviour
{
public class AccountRefreshLogin : MonoBehaviour {
[SerializeField] private TMP_Text refreshLoginStatusText;
[SerializeField] private TMP_InputField refreshLoginUsernameInput;
[SerializeField] private TMP_InputField refreshLoginPasswordInput;
[SerializeField] private Button refreshLoginBackButton;
[SerializeField] private Button refreshLoginSubmitButton;
void Awake()
{
void Awake() {
refreshLoginUsernameInput.onSelect.AddListener((_) => refreshLoginUsernameInput.caretPosition = refreshLoginUsernameInput.text.Length);
refreshLoginPasswordInput.onSelect.AddListener((_) => refreshLoginPasswordInput.caretPosition = refreshLoginPasswordInput.text.Length);
@@ -22,14 +20,12 @@ public class AccountRefreshLogin : MonoBehaviour
refreshLoginSubmitButton.onClick.AddListener(() => RefreshLogin());
}
void OnEnable()
{
void OnEnable() {
refreshLoginUsernameInput.text = "";
refreshLoginPasswordInput.text = "";
}
async void RefreshLogin()
{
async void RefreshLogin() {
refreshLoginBackButton.interactable = false;
refreshLoginSubmitButton.interactable = false;
WWWForm dataForm = new();
@@ -40,24 +36,20 @@ public class AccountRefreshLogin : MonoBehaviour
request.SetRequestHeader("ClientVersion", Application.version);
request.SetRequestHeader("ClientPlatform", Application.platform.ToString());
await request.SendWebRequest();
if (request.downloadHandler.text == null)
{
if (request.downloadHandler.text == null) {
refreshLoginBackButton.interactable = true;
refreshLoginSubmitButton.interactable = true;
Tools.UpdateStatusText(refreshLoginStatusText, "Failed to make HTTP request", Color.red);
return;
}
var jsonResponse = JObject.Parse(request.downloadHandler.text);
if ((bool)jsonResponse["success"])
{
if ((bool)jsonResponse["success"]) {
BazookaManager.Instance.SetAccountSession((string)jsonResponse["data"]["session"]);
BazookaManager.Instance.SetAccountName((string)jsonResponse["data"]["username"]);
BazookaManager.Instance.SetAccountID(BigInteger.Parse((string)jsonResponse["data"]["id"]));
AccountHandler.instance.SwitchPanel(0);
Tools.UpdateStatusText(refreshLoginStatusText, "", Color.red);
}
else
{
} else {
Tools.UpdateStatusText(refreshLoginStatusText, (string)jsonResponse["message"], Color.red);
}
refreshLoginBackButton.interactable = true;
+10 -21
View File
@@ -4,8 +4,7 @@ using UnityEngine;
using UnityEngine.Networking;
using UnityEngine.UI;
public class AccountRegister : MonoBehaviour
{
public class AccountRegister : MonoBehaviour {
[SerializeField] private TMP_Text registerPanelStatusText;
[SerializeField] private TMP_InputField registerUsernameInput;
[SerializeField] private TMP_InputField registerEmailInput;
@@ -16,8 +15,7 @@ public class AccountRegister : MonoBehaviour
[SerializeField] private Button registerBackButton;
[SerializeField] private Button registerSubmitButton;
void Awake()
{
void Awake() {
registerUsernameInput.onSelect.AddListener((_) => registerUsernameInput.caretPosition = registerUsernameInput.text.Length);
registerEmailInput.onSelect.AddListener((_) => registerEmailInput.caretPosition = registerEmailInput.text.Length);
registerRetypeEmailInput.onSelect.AddListener((_) => registerRetypeEmailInput.caretPosition = registerRetypeEmailInput.text.Length);
@@ -29,8 +27,7 @@ public class AccountRegister : MonoBehaviour
registerSubmitButton.onClick.AddListener(() => SubmitRegister());
}
void OnEnable()
{
void OnEnable() {
registerUsernameInput.text = "";
registerEmailInput.text = "";
registerRetypeEmailInput.text = "";
@@ -40,8 +37,7 @@ public class AccountRegister : MonoBehaviour
registerPanelStatusText.text = "";
}
async void SubmitRegister()
{
async void SubmitRegister() {
if (
registerUsernameInput.text == string.Empty ||
registerEmailInput.text == string.Empty ||
@@ -49,18 +45,15 @@ public class AccountRegister : MonoBehaviour
registerPasswordInput.text == string.Empty ||
registerRetypePasswordInput.text == string.Empty ||
registerVerifyCodeInput.text == string.Empty
)
{
) {
Tools.UpdateStatusText(registerPanelStatusText, "All input fields must be filled", Color.red);
return;
}
if (registerEmailInput.text != registerRetypeEmailInput.text)
{
if (registerEmailInput.text != registerRetypeEmailInput.text) {
Tools.UpdateStatusText(registerPanelStatusText, "Emails don't match", Color.red);
return;
}
if (registerPasswordInput.text != registerRetypePasswordInput.text)
{
if (registerPasswordInput.text != registerRetypePasswordInput.text) {
Tools.UpdateStatusText(registerPanelStatusText, "Passwords don't match", Color.red);
return;
}
@@ -77,20 +70,16 @@ public class AccountRegister : MonoBehaviour
request.SetRequestHeader("ClientVersion", Application.version);
request.SetRequestHeader("ClientPlatform", Application.platform.ToString());
await request.SendWebRequest();
if (request.downloadHandler.text == null)
{
if (request.downloadHandler.text == null) {
registerBackButton.interactable = true;
registerSubmitButton.interactable = true;
Tools.UpdateStatusText(registerPanelStatusText, "Failed to make HTTP request", Color.red);
return;
}
var jsonResponse = JObject.Parse(request.downloadHandler.text);
if ((bool)jsonResponse["success"])
{
if ((bool)jsonResponse["success"]) {
AccountHandler.instance.SwitchPanel(2);
}
else
{
} else {
Tools.UpdateStatusText(registerPanelStatusText, (string)jsonResponse["message"], Color.red);
}
registerBackButton.interactable = true;
+117 -237
View File
@@ -7,30 +7,23 @@ using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using UnityEngine;
public class BazookaManager : MonoBehaviour
{
public class BazookaManager : MonoBehaviour {
public static BazookaManager Instance;
private bool firstLoadDone = false;
public JObject saveFile = new()
{
public JObject saveFile = new() {
["version"] = "1"
};
public List<MarketplaceIcon> iconCache = new();
void Awake()
{
if (Instance == null)
{
void Awake() {
if (Instance == null) {
Instance = this;
DontDestroyOnLoad(gameObject);
if (!firstLoadDone)
{
try
{
if (!firstLoadDone) {
try {
var oldSave = Path.Join(Application.persistentDataPath, OldSavefileEncryption.BAZOOKA_MANAGER_FILE_KEY + ".dat");
var newSave = Path.Join(Application.persistentDataPath, "savefile.json");
if (File.Exists(oldSave) && !File.Exists(newSave))
{
if (File.Exists(oldSave) && !File.Exists(newSave)) {
File.WriteAllBytes(newSave, Encoding.UTF8.GetBytes(OldSavefileEncryption.DecryptRaw(File.ReadAllBytes(oldSave))));
File.Delete(oldSave);
}
@@ -40,15 +33,11 @@ public class BazookaManager : MonoBehaviour
firstLoadDone = true;
var save = LoadObject("savefile");
var cache = LoadArray("cache");
if (save != null)
{
if (save["version"] != null && (save["version"].ToString() == "0" || save["version"].ToString() == "1"))
{
if (save != null) {
if (save["version"] != null && (save["version"].ToString() == "0" || save["version"].ToString() == "1")) {
saveFile = save;
if (saveFile["version"].ToString() == "0")
{
if (saveFile["bird"]["customIcon"]["data"] != null)
{
if (saveFile["version"].ToString() == "0") {
if (saveFile["bird"]["customIcon"]["data"] != null) {
var data = saveFile["bird"]["customIcon"]["data"];
var customData = GetCustomBirdIconData();
saveFile["bird"]["customIcon"]["data"].Parent.Remove();
@@ -61,50 +50,40 @@ public class BazookaManager : MonoBehaviour
}
}
}
if (cache != null)
{
if (cache != null) {
var tempIconCache = cache.ToObject<List<MarketplaceIcon>>() ?? new List<MarketplaceIcon>();
foreach (var icon in tempIconCache)
{
iconCache.Add(new MarketplaceIcon
{
foreach (var icon in tempIconCache) {
iconCache.Add(new MarketplaceIcon {
Data = icon.Data.Substring(0, icon.Data.Length - 128),
ID = icon.ID
});
}
}
}
}
else
{
} else {
Destroy(gameObject);
}
}
void OnApplicationQuit()
{
void OnApplicationQuit() {
Save("savefile", saveFile);
var cacheIcons = new JArray();
foreach (var icon in iconCache)
cacheIcons.Add(new JObject
{
cacheIcons.Add(new JObject {
["data"] = icon.Data + Tools.Sha512Sum(Convert.FromBase64String(icon.Data)),
["id"] = icon.ID
});
Save("cache", cacheIcons);
}
void OnApplicationPause(bool pause)
{
if (pause)
{
void OnApplicationPause(bool pause) {
if (pause) {
Save("savefile", saveFile);
var cacheIcons = new JArray();
foreach (var icon in iconCache)
cacheIcons.Add(new JObject
{
cacheIcons.Add(new JObject {
["data"] = icon.Data + Tools.Sha512Sum(Convert.FromBase64String(icon.Data)),
["id"] = icon.ID
});
@@ -112,52 +91,39 @@ public class BazookaManager : MonoBehaviour
}
}
public JObject LoadObject(string saveName)
{
public JObject LoadObject(string saveName) {
string path = Path.Join(Application.persistentDataPath, saveName + ".json");
if (!File.Exists(path))
{
if (!File.Exists(path)) {
return null;
}
else
{
try
{
} else {
try {
var tempSaveFile = JObject.Parse(File.ReadAllText(path));
if (tempSaveFile != null) return tempSaveFile;
}
catch (Exception e)
{
catch (Exception e) {
Debug.LogWarning("Failed to load save file: " + e);
}
}
return null;
}
public JArray LoadArray(string saveName)
{
public JArray LoadArray(string saveName) {
string path = Path.Join(Application.persistentDataPath, saveName + ".json");
if (!File.Exists(path))
{
if (!File.Exists(path)) {
return null;
}
else
{
try
{
} else {
try {
var tempSaveFile = JArray.Parse(File.ReadAllText(path));
if (tempSaveFile != null) return tempSaveFile;
}
catch (Exception e)
{
catch (Exception e) {
Debug.LogWarning("Failed to load save file: " + e);
}
}
return null;
}
public void Save(string saveName, JObject save)
{
public void Save(string saveName, JObject save) {
string path = Path.Join(Application.persistentDataPath, saveName + ".json");
var encoded = Encoding.UTF8.GetBytes(save.ToString(Formatting.Indented));
if (encoded == null) return;
@@ -166,8 +132,7 @@ public class BazookaManager : MonoBehaviour
fileStream.Flush(true);
}
public void Save(string saveName, JArray save)
{
public void Save(string saveName, JArray save) {
string path = Path.Join(Application.persistentDataPath, saveName + ".json");
var encoded = Encoding.UTF8.GetBytes(save.ToString(Formatting.Indented));
if (encoded == null) return;
@@ -176,10 +141,8 @@ public class BazookaManager : MonoBehaviour
fileStream.Flush(true);
}
public void ResetSave()
{
saveFile = new JObject
{
public void ResetSave() {
saveFile = new JObject {
["version"] = "1"
};
Save("savefile", saveFile);
@@ -187,73 +150,62 @@ public class BazookaManager : MonoBehaviour
//Random stuff
public void SetLikedPosts(JArray value)
{
public void SetLikedPosts(JArray value) {
saveFile["likedPosts"] = value;
}
public JArray GetLikedPosts()
{
public JArray GetLikedPosts() {
if (saveFile["likedPosts"] == null) return new JArray();
return JArray.Parse(saveFile["likedPosts"].ToString());
}
//Bird stuff
public void SetBirdIcon(int value)
{
public void SetBirdIcon(int value) {
if (saveFile["bird"] == null) saveFile["bird"] = new JObject();
saveFile["bird"]["icon"] = value;
}
public void UnsetBirdIcon()
{
public void UnsetBirdIcon() {
if (saveFile["bird"] == null) return;
if (saveFile["bird"]["icon"] == null) return;
(saveFile["bird"] as JObject)?.Remove("icon");
}
public int GetBirdIcon()
{
public int GetBirdIcon() {
if (saveFile["bird"] == null) return 1;
if (saveFile["bird"]["icon"] == null) return 1;
return int.Parse(saveFile["bird"]["icon"].ToString());
}
public void SetBirdOverlay(int value)
{
public void SetBirdOverlay(int value) {
if (saveFile["bird"] == null) saveFile["bird"] = new JObject();
saveFile["bird"]["overlay"] = value;
}
public void UnsetBirdOverlay()
{
public void UnsetBirdOverlay() {
if (saveFile["bird"] == null) return;
if (saveFile["bird"]["overlay"] == null) return;
(saveFile["bird"] as JObject)?.Remove("overlay");
}
public int GetBirdOverlay()
{
public int GetBirdOverlay() {
if (saveFile["bird"] == null) return 0;
if (saveFile["bird"]["overlay"] == null) return 0;
return int.Parse(saveFile["bird"]["overlay"].ToString());
}
public void SetCustomBirdIconData(MarketplaceIconStorageType value)
{
public void SetCustomBirdIconData(MarketplaceIconStorageType value) {
if (saveFile["bird"] == null) saveFile["bird"] = new JObject();
saveFile["bird"]["customIcon"] = JObject.FromObject(value);
}
public void UnsetCustomBirdIconData()
{
public void UnsetCustomBirdIconData() {
if (saveFile["bird"] == null) return;
if (saveFile["bird"]["customIcon"] == null) return;
(saveFile["bird"] as JObject)?.Remove("customIcon");
}
public MarketplaceIconStorageType GetCustomBirdIconData()
{
public MarketplaceIconStorageType GetCustomBirdIconData() {
if (saveFile["bird"] == null) return new();
if (saveFile["bird"]["customIcon"] == null) return new();
return saveFile["bird"]["customIcon"].ToObject<MarketplaceIconStorageType>();
@@ -261,212 +213,182 @@ public class BazookaManager : MonoBehaviour
//Settings stuff
public void SetSettingFullScreen(bool value)
{
public void SetSettingFullScreen(bool value) {
if (saveFile["settings"] == null) saveFile["settings"] = new JObject();
saveFile["settings"]["fullScreen"] = value;
}
public bool GetSettingFullScreen()
{
public bool GetSettingFullScreen() {
if (saveFile["settings"] == null) return true;
if (saveFile["settings"]["fullScreen"] == null) return true;
return bool.Parse(saveFile["settings"]["fullScreen"].ToString());
}
public void SetSettingShowFPS(bool value)
{
public void SetSettingShowFPS(bool value) {
if (saveFile["settings"] == null) saveFile["settings"] = new JObject();
saveFile["settings"]["showFps"] = value;
}
public bool GetSettingShowFPS()
{
public bool GetSettingShowFPS() {
if (saveFile["settings"] == null) return false;
if (saveFile["settings"]["showFps"] == null) return false;
return bool.Parse(saveFile["settings"]["showFps"].ToString());
}
public void SetSettingVsync(bool value)
{
public void SetSettingVsync(bool value) {
if (saveFile["settings"] == null) saveFile["settings"] = new JObject();
saveFile["settings"]["vsync"] = value;
}
public bool GetSettingVsync()
{
public bool GetSettingVsync() {
if (saveFile["settings"] == null) return true;
if (saveFile["settings"]["vsync"] == null) return true;
return bool.Parse(saveFile["settings"]["vsync"].ToString());
}
public void SetSettingHideSocials(bool value)
{
public void SetSettingHideSocials(bool value) {
if (saveFile["settings"] == null) saveFile["settings"] = new JObject();
saveFile["settings"]["hideSocials"] = value;
}
public bool? GetSettingHideSocials()
{
public bool? GetSettingHideSocials() {
if (saveFile["settings"] == null) return null;
if (saveFile["settings"]["hideSocials"] == null) return null;
return bool.Parse(saveFile["settings"]["hideSocials"].ToString());
}
public void SetSettingRandomMusic(bool value)
{
public void SetSettingRandomMusic(bool value) {
if (saveFile["settings"] == null) saveFile["settings"] = new JObject();
saveFile["settings"]["randomMusic"] = value;
}
public bool GetSettingRandomMusic()
{
public bool GetSettingRandomMusic() {
if (saveFile["settings"] == null) return true;
if (saveFile["settings"]["randomMusic"] == null) return true;
return bool.Parse(saveFile["settings"]["randomMusic"].ToString());
}
public void SetSettingMusicVolume(float value)
{
public void SetSettingMusicVolume(float value) {
if (saveFile["settings"] == null) saveFile["settings"] = new JObject();
saveFile["settings"]["musicVolume"] = value;
}
public float GetSettingMusicVolume()
{
public float GetSettingMusicVolume() {
if (saveFile["settings"] == null) return 1f;
if (saveFile["settings"]["musicVolume"] == null) return 1f;
return float.Parse(saveFile["settings"]["musicVolume"].ToString());
}
public void SetSettingSFXVolume(float value)
{
public void SetSettingSFXVolume(float value) {
if (saveFile["settings"] == null) saveFile["settings"] = new JObject();
saveFile["settings"]["sfxVolume"] = value;
}
public float GetSettingSFXVolume()
{
public float GetSettingSFXVolume() {
if (saveFile["settings"] == null) return 1f;
if (saveFile["settings"]["sfxVolume"] == null) return 1f;
return float.Parse(saveFile["settings"]["sfxVolume"].ToString());
}
public void SetColorSettingBackground(JArray value)
{
public void SetColorSettingBackground(JArray value) {
if (saveFile["settings"] == null) saveFile["settings"] = new JObject();
if (saveFile["settings"]["colors"] == null) saveFile["settings"]["colors"] = new JObject();
saveFile["settings"]["colors"]["background"] = value;
}
public JArray GetColorSettingBackground()
{
public JArray GetColorSettingBackground() {
if (saveFile["settings"] == null) return new JArray(58, 58, 58);
if (saveFile["settings"]["colors"] == null) return new JArray(58, 58, 58);
if (saveFile["settings"]["colors"]["background"] == null) return new JArray(58, 58, 58);
return JArray.Parse(saveFile["settings"]["colors"]["background"].ToString());
}
public void SetColorSettingMenuBackground(JArray value)
{
public void SetColorSettingMenuBackground(JArray value) {
if (saveFile["settings"] == null) saveFile["settings"] = new JObject();
if (saveFile["settings"]["colors"] == null) saveFile["settings"]["colors"] = new JObject();
saveFile["settings"]["colors"]["menuBackground"] = value;
}
public JArray GetColorSettingMenuBackground()
{
public JArray GetColorSettingMenuBackground() {
if (saveFile["settings"] == null) return new JArray(24, 24, 24);
if (saveFile["settings"]["colors"] == null) return new JArray(24, 24, 24);
if (saveFile["settings"]["colors"]["menuBackground"] == null) return new JArray(24, 24, 24);
return JArray.Parse(saveFile["settings"]["colors"]["menuBackground"].ToString());
}
public void SetColorSettingButton(JArray value)
{
public void SetColorSettingButton(JArray value) {
if (saveFile["settings"] == null) saveFile["settings"] = new JObject();
if (saveFile["settings"]["colors"] == null) saveFile["settings"]["colors"] = new JObject();
saveFile["settings"]["colors"]["button"] = value;
}
public JArray GetColorSettingButton()
{
public JArray GetColorSettingButton() {
if (saveFile["settings"] == null) return new JArray(255, 255, 255);
if (saveFile["settings"]["colors"] == null) return new JArray(255, 255, 255);
if (saveFile["settings"]["colors"]["button"] == null) return new JArray(255, 255, 255);
return JArray.Parse(saveFile["settings"]["colors"]["button"].ToString());
}
public void SetColorSettingText(JArray value)
{
public void SetColorSettingText(JArray value) {
if (saveFile["settings"] == null) saveFile["settings"] = new JObject();
if (saveFile["settings"]["colors"] == null) saveFile["settings"]["colors"] = new JObject();
saveFile["settings"]["colors"]["text"] = value;
}
public JArray GetColorSettingText()
{
public JArray GetColorSettingText() {
if (saveFile["settings"] == null) return new JArray(255, 255, 255);
if (saveFile["settings"]["colors"] == null) return new JArray(255, 255, 255);
if (saveFile["settings"]["colors"]["text"] == null) return new JArray(255, 255, 255);
return JArray.Parse(saveFile["settings"]["colors"]["text"].ToString());
}
public void SetColorSettingButtonContent(JArray value)
{
public void SetColorSettingButtonContent(JArray value) {
if (saveFile["settings"] == null) saveFile["settings"] = new JObject();
if (saveFile["settings"]["colors"] == null) saveFile["settings"]["colors"] = new JObject();
saveFile["settings"]["colors"]["buttonColor"] = value;
}
public JArray GetColorSettingButtonContent()
{
public JArray GetColorSettingButtonContent() {
if (saveFile["settings"] == null) return new JArray(0, 0, 0);
if (saveFile["settings"]["colors"] == null) return new JArray(0, 0, 0);
if (saveFile["settings"]["colors"]["buttonColor"] == null) return new JArray(0, 0, 0);
return JArray.Parse(saveFile["settings"]["colors"]["buttonColor"].ToString());
}
public void SetColorSettingIcon(JArray value)
{
public void SetColorSettingIcon(JArray value) {
if (saveFile["settings"] == null) saveFile["settings"] = new JObject();
if (saveFile["settings"]["colors"] == null) saveFile["settings"]["colors"] = new JObject();
saveFile["settings"]["colors"]["icon"] = value;
}
public JArray GetColorSettingIcon()
{
public JArray GetColorSettingIcon() {
if (saveFile["settings"] == null) return new JArray(255, 255, 255);
if (saveFile["settings"]["colors"] == null) return new JArray(255, 255, 255);
if (saveFile["settings"]["colors"]["icon"] == null) return new JArray(255, 255, 255);
return JArray.Parse(saveFile["settings"]["colors"]["icon"].ToString());
}
public void UnsetColorSettingIcon()
{
public void UnsetColorSettingIcon() {
if (saveFile["settings"] == null) return;
if (saveFile["settings"]["colors"] == null) return;
if (saveFile["settings"]["colors"]["icon"] == null) return;
(saveFile["settings"]["colors"] as JObject)?.Remove("icon");
}
public void SetColorSettingOverlay(JArray value)
{
public void SetColorSettingOverlay(JArray value) {
if (saveFile["settings"] == null) saveFile["settings"] = new JObject();
if (saveFile["settings"]["colors"] == null) saveFile["settings"]["colors"] = new JObject();
saveFile["settings"]["colors"]["overlay"] = value;
}
public JArray GetColorSettingOverlay()
{
public JArray GetColorSettingOverlay() {
if (saveFile["settings"] == null) return new JArray(255, 255, 255);
if (saveFile["settings"]["colors"] == null) return new JArray(255, 255, 255);
if (saveFile["settings"]["colors"]["overlay"] == null) return new JArray(255, 255, 255);
return JArray.Parse(saveFile["settings"]["colors"]["overlay"].ToString());
}
public void UnsetColorSettingOverlay()
{
public void UnsetColorSettingOverlay() {
if (saveFile["settings"] == null) return;
if (saveFile["settings"]["colors"] == null) return;
if (saveFile["settings"]["colors"]["overlay"] == null) return;
@@ -475,270 +397,228 @@ public class BazookaManager : MonoBehaviour
//Account stuff
public void SetAccountSession(string value)
{
public void SetAccountSession(string value) {
if (saveFile["account"] == null) saveFile["account"] = new JObject();
saveFile["account"]["session"] = value;
}
public string GetAccountSession()
{
public string GetAccountSession() {
if (saveFile["account"] == null) return null;
if (saveFile["account"]["session"] == null) return null;
return saveFile["account"]["session"].ToString();
}
public void UnsetAccountSession()
{
public void UnsetAccountSession() {
if (saveFile["account"] == null) return;
(saveFile["account"] as JObject)?.Remove("session");
}
public void SetAccountName(string value)
{
public void SetAccountName(string value) {
if (saveFile["account"] == null) saveFile["account"] = new JObject();
saveFile["account"]["name"] = value;
}
public string GetAccountName()
{
public string GetAccountName() {
if (saveFile["account"] == null) return null;
if (saveFile["account"]["name"] == null) return null;
return saveFile["account"]["name"].ToString();
}
public void UnsetAccountName()
{
public void UnsetAccountName() {
if (saveFile["account"] == null) return;
(saveFile["account"] as JObject)?.Remove("name");
}
public void SetAccountID(BigInteger value)
{
public void SetAccountID(BigInteger value) {
if (saveFile["account"] == null) saveFile["account"] = new JObject();
saveFile["account"]["id"] = value.ToString();
}
public BigInteger? GetAccountID()
{
public BigInteger? GetAccountID() {
if (saveFile["account"] == null) return null;
if (saveFile["account"]["id"] == null) return null;
return BigInteger.Parse(saveFile["account"]["id"].ToString());
}
public void UnsetAccountID()
{
public void UnsetAccountID() {
if (saveFile["account"] == null) return;
(saveFile["account"] as JObject)?.Remove("id");
}
//Game store stuff
public void SetGameStoreHighScore(BigInteger value)
{
public void SetGameStoreHighScore(BigInteger value) {
if (saveFile["gameStore"] == null) saveFile["gameStore"] = new JObject();
saveFile["gameStore"]["highScore"] = value.ToString();
}
public BigInteger GetGameStoreHighScore()
{
public BigInteger GetGameStoreHighScore() {
if (saveFile["gameStore"] == null) return 0;
if (saveFile["gameStore"]["highScore"] == null) return 0;
return BigInteger.Parse(saveFile["gameStore"]["highScore"].ToString());
}
public void UnsetGameStoreHighScore()
{
public void UnsetGameStoreHighScore() {
if (saveFile["gameStore"] == null) return;
(saveFile["gameStore"] as JObject)?.Remove("highScore");
}
public void SetGameStoreTotalAttepts(BigInteger value)
{
public void SetGameStoreTotalAttepts(BigInteger value) {
if (saveFile["gameStore"] == null) saveFile["gameStore"] = new JObject();
saveFile["gameStore"]["totalAttempts"] = value.ToString();
}
public BigInteger GetGameStoreTotalAttepts()
{
public BigInteger GetGameStoreTotalAttepts() {
if (saveFile["gameStore"] == null) return 0;
if (saveFile["gameStore"]["totalAttempts"] == null) return 0;
return BigInteger.Parse(saveFile["gameStore"]["totalAttempts"].ToString());
}
public void UnsetGameStoreTotalAttepts()
{
public void UnsetGameStoreTotalAttepts() {
if (saveFile["gameStore"] == null) return;
(saveFile["gameStore"] as JObject)?.Remove("totalAttempts");
}
public void SetGameStoreTotalNormalBerries(BigInteger value)
{
public void SetGameStoreTotalNormalBerries(BigInteger value) {
if (saveFile["gameStore"] == null) saveFile["gameStore"] = new JObject();
saveFile["gameStore"]["totalNormalBerries"] = value.ToString();
}
public BigInteger GetGameStoreTotalNormalBerries()
{
public BigInteger GetGameStoreTotalNormalBerries() {
if (saveFile["gameStore"] == null) return 0;
if (saveFile["gameStore"]["totalNormalBerries"] == null) return 0;
return BigInteger.Parse(saveFile["gameStore"]["totalNormalBerries"].ToString());
}
public void UnsetGameStoreTotalNormalBerries()
{
public void UnsetGameStoreTotalNormalBerries() {
if (saveFile["gameStore"] == null) return;
(saveFile["gameStore"] as JObject)?.Remove("totalNormalBerries");
}
public void SetGameStoreTotalPoisonBerries(BigInteger value)
{
public void SetGameStoreTotalPoisonBerries(BigInteger value) {
if (saveFile["gameStore"] == null) saveFile["gameStore"] = new JObject();
saveFile["gameStore"]["totalPoisonBerries"] = value.ToString();
}
public BigInteger GetGameStoreTotalPoisonBerries()
{
public BigInteger GetGameStoreTotalPoisonBerries() {
if (saveFile["gameStore"] == null) return 0;
if (saveFile["gameStore"]["totalPoisonBerries"] == null) return 0;
return BigInteger.Parse(saveFile["gameStore"]["totalPoisonBerries"].ToString());
}
public void UnsetGameStoreTotalPoisonBerries()
{
public void UnsetGameStoreTotalPoisonBerries() {
if (saveFile["gameStore"] == null) return;
(saveFile["gameStore"] as JObject)?.Remove("totalPoisonBerries");
}
public void SetGameStoreTotalSlowBerries(BigInteger value)
{
public void SetGameStoreTotalSlowBerries(BigInteger value) {
if (saveFile["gameStore"] == null) saveFile["gameStore"] = new JObject();
saveFile["gameStore"]["totalSlowBerries"] = value.ToString();
}
public BigInteger GetGameStoreTotalSlowBerries()
{
public BigInteger GetGameStoreTotalSlowBerries() {
if (saveFile["gameStore"] == null) return 0;
if (saveFile["gameStore"]["totalSlowBerries"] == null) return 0;
return BigInteger.Parse(saveFile["gameStore"]["totalSlowBerries"].ToString());
}
public void UnsetGameStoreTotalSlowBerries()
{
public void UnsetGameStoreTotalSlowBerries() {
if (saveFile["gameStore"] == null) return;
(saveFile["gameStore"] as JObject)?.Remove("totalSlowBerries");
}
public void SetGameStoreTotalUltraBerries(BigInteger value)
{
public void SetGameStoreTotalUltraBerries(BigInteger value) {
if (saveFile["gameStore"] == null) saveFile["gameStore"] = new JObject();
saveFile["gameStore"]["totalUltraBerries"] = value.ToString();
}
public BigInteger GetGameStoreTotalUltraBerries()
{
public BigInteger GetGameStoreTotalUltraBerries() {
if (saveFile["gameStore"] == null) return 0;
if (saveFile["gameStore"]["totalUltraBerries"] == null) return 0;
return BigInteger.Parse(saveFile["gameStore"]["totalUltraBerries"].ToString());
}
public void UnsetGameStoreTotalUltraBerries()
{
public void UnsetGameStoreTotalUltraBerries() {
if (saveFile["gameStore"] == null) return;
(saveFile["gameStore"] as JObject)?.Remove("totalUltraBerries");
}
public void SetGameStoreTotalSpeedyBerries(BigInteger value)
{
public void SetGameStoreTotalSpeedyBerries(BigInteger value) {
if (saveFile["gameStore"] == null) saveFile["gameStore"] = new JObject();
saveFile["gameStore"]["totalSpeedyBerries"] = value.ToString();
}
public BigInteger GetGameStoreTotalSpeedyBerries()
{
public BigInteger GetGameStoreTotalSpeedyBerries() {
if (saveFile["gameStore"] == null) return 0;
if (saveFile["gameStore"]["totalSpeedyBerries"] == null) return 0;
return BigInteger.Parse(saveFile["gameStore"]["totalSpeedyBerries"].ToString());
}
public void UnsetGameStoreTotalSpeedyBerries()
{
public void UnsetGameStoreTotalSpeedyBerries() {
if (saveFile["gameStore"] == null) return;
(saveFile["gameStore"] as JObject)?.Remove("totalSpeedyBerries");
}
public void SetGameStoreTotalCoinBerries(BigInteger value)
{
public void SetGameStoreTotalCoinBerries(BigInteger value) {
if (saveFile["gameStore"] == null) saveFile["gameStore"] = new JObject();
saveFile["gameStore"]["totalCoinBerries"] = value.ToString();
}
public BigInteger GetGameStoreTotalCoinBerries()
{
public BigInteger GetGameStoreTotalCoinBerries() {
if (saveFile["gameStore"] == null) return 0;
if (saveFile["gameStore"]["totalCoinBerries"] == null) return 0;
return BigInteger.Parse(saveFile["gameStore"]["totalCoinBerries"].ToString());
}
public void UnsetGameStoreTotalCoinBerries()
{
public void UnsetGameStoreTotalCoinBerries() {
if (saveFile["gameStore"] == null) return;
(saveFile["gameStore"] as JObject)?.Remove("totalCoinBerries");
}
public void SetGameStoreTotalRandomBerries(BigInteger value)
{
public void SetGameStoreTotalRandomBerries(BigInteger value) {
if (saveFile["gameStore"] == null) saveFile["gameStore"] = new JObject();
saveFile["gameStore"]["totalRandomBerries"] = value.ToString();
}
public BigInteger GetGameStoreTotalRandomBerries()
{
public BigInteger GetGameStoreTotalRandomBerries() {
if (saveFile["gameStore"] == null) return 0;
if (saveFile["gameStore"]["totalRandomBerries"] == null) return 0;
return BigInteger.Parse(saveFile["gameStore"]["totalRandomBerries"].ToString());
}
public void UnsetGameStoreTotalRandomBerries()
{
public void UnsetGameStoreTotalRandomBerries() {
if (saveFile["gameStore"] == null) return;
(saveFile["gameStore"] as JObject)?.Remove("totalRandomBerries");
}
public void SetGameStoreTotalAntiBerries(BigInteger value)
{
public void SetGameStoreTotalAntiBerries(BigInteger value) {
if (saveFile["gameStore"] == null) saveFile["gameStore"] = new JObject();
saveFile["gameStore"]["totalAntiBerries"] = value.ToString();
}
public BigInteger GetGameStoreTotalAntiBerries()
{
public BigInteger GetGameStoreTotalAntiBerries() {
if (saveFile["gameStore"] == null) return 0;
if (saveFile["gameStore"]["totalAntiBerries"] == null) return 0;
return BigInteger.Parse(saveFile["gameStore"]["totalAntiBerries"].ToString());
}
public void UnsetGameStoreTotalAntiBerries()
{
public void UnsetGameStoreTotalAntiBerries() {
if (saveFile["gameStore"] == null) return;
(saveFile["gameStore"] as JObject)?.Remove("totalAntiBerries");
}
public void SetGameStoreTotalGoldenBerries(BigInteger value)
{
public void SetGameStoreTotalGoldenBerries(BigInteger value) {
if (saveFile["gameStore"] == null) saveFile["gameStore"] = new JObject();
saveFile["gameStore"]["totalGoldenBerries"] = value.ToString();
}
public BigInteger GetGameStoreTotalGoldenBerries()
{
public BigInteger GetGameStoreTotalGoldenBerries() {
if (saveFile["gameStore"] == null) return 0;
if (saveFile["gameStore"]["totalGoldenBerries"] == null) return 0;
return BigInteger.Parse(saveFile["gameStore"]["totalGoldenBerries"].ToString());
}
public void UnsetGameStoreTotalGoldenBerries()
{
public void UnsetGameStoreTotalGoldenBerries() {
if (saveFile["gameStore"] == null) return;
(saveFile["gameStore"] as JObject)?.Remove("totalGoldenBerries");
}
+13 -27
View File
@@ -2,64 +2,52 @@ using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.InputSystem;
public class BouncyButton : MonoBehaviour, IPointerEnterHandler, IPointerExitHandler
{
public class BouncyButton : MonoBehaviour, IPointerEnterHandler, IPointerExitHandler {
private bool isHovered = false;
private bool isHeld = false;
private bool didBounce = false;
private Vector3 originalScale;
private Vector3 finalScale;
void Start()
{
void Start() {
originalScale = transform.localScale;
finalScale = originalScale * 1.1f;
}
public void OnPointerEnter(PointerEventData eventData) => isHovered = true;
public void OnPointerExit(PointerEventData eventData)
{
public void OnPointerExit(PointerEventData eventData) {
isHovered = false;
ResetScale();
}
void OnDisable()
{
void OnDisable() {
isHovered = false;
ResetScale();
}
void Update()
{
if (Application.isMobilePlatform)
{
void Update() {
if (Application.isMobilePlatform) {
isHeld = Touchscreen.current != null && Touchscreen.current.press.isPressed;
}
else
{
} else {
isHeld = Mouse.current != null && Mouse.current.leftButton.isPressed;
}
if (isHovered && isHeld && !didBounce)
{
if (isHovered && isHeld && !didBounce) {
StartCoroutine(BounceOnce());
didBounce = true;
}
if ((!isHovered || !isHeld) && didBounce)
{
if ((!isHovered || !isHeld) && didBounce) {
ResetScale();
}
}
void ResetScale()
{
void ResetScale() {
StopAllCoroutines();
transform.localScale = originalScale;
didBounce = false;
}
System.Collections.IEnumerator BounceOnce()
{
System.Collections.IEnumerator BounceOnce() {
float t = 0.125f;
Vector3 s1 = originalScale * 1.12f;
Vector3 s2 = originalScale * 1.06f;
@@ -72,11 +60,9 @@ public class BouncyButton : MonoBehaviour, IPointerEnterHandler, IPointerExitHan
transform.localScale = s3;
}
System.Collections.IEnumerator LerpScale(Vector3 from, Vector3 to, float duration)
{
System.Collections.IEnumerator LerpScale(Vector3 from, Vector3 to, float duration) {
float elapsed = 0f;
while (elapsed < duration)
{
while (elapsed < duration) {
elapsed += Time.deltaTime;
float p = elapsed / duration;
transform.localScale = Vector3.Lerp(from, to, p);
+2 -4
View File
@@ -1,13 +1,11 @@
using UnityEngine;
public class BouncyPanel : MonoBehaviour
{
public class BouncyPanel : MonoBehaviour {
[SerializeField] private float frequency = 8f;
[SerializeField] private float minSize = 1f;
[SerializeField] private float maxSize = 1.1f;
void Update()
{
void Update() {
float newsize = (Mathf.Sin(Time.time * frequency) + 1f) / 2f;
var size = Mathf.Lerp(minSize, maxSize, newsize);
gameObject.transform.localScale = new(size, size, size);
+4 -8
View File
@@ -2,8 +2,7 @@ using TMPro;
using UnityEngine;
[RequireComponent(typeof(TextMeshProUGUI))]
public class BouncyText : MonoBehaviour
{
public class BouncyText : MonoBehaviour {
[SerializeField] private float frequency = 2f;
[SerializeField] private float minSize = 10f;
[SerializeField] private float maxSize = 12f;
@@ -11,19 +10,16 @@ public class BouncyText : MonoBehaviour
private TextMeshProUGUI text;
private float startSize = 0;
void Awake()
{
void Awake() {
text = GetComponent<TextMeshProUGUI>();
if (add)
{
if (add) {
text.ForceMeshUpdate();
startSize = text.fontSize;
text.enableAutoSizing = false;
}
}
void Update()
{
void Update() {
float newsize = (Mathf.Sin(Time.time * frequency) + 1f) / 2f;
text.fontSize = Mathf.Lerp(add ? startSize : minSize, maxSize + (add ? startSize : 0), newsize);
}
+2 -4
View File
@@ -1,13 +1,11 @@
using TMPro;
using UnityEngine;
public class ImageColorSync : MonoBehaviour
{
public class ImageColorSync : MonoBehaviour {
[SerializeField] private TMP_Text originalText;
[SerializeField] private TMP_Text toSync;
void Update()
{
void Update() {
Color baseColor = originalText.color;
Color graphicColor = originalText.canvasRenderer.GetColor();
+3 -6
View File
@@ -2,14 +2,11 @@ using UnityEngine;
using UnityEngine.SceneManagement;
using UnityEngine.UI;
public class ButtonToScene : MonoBehaviour
{
public class ButtonToScene : MonoBehaviour {
[SerializeField] private string sceneName;
void Awake()
{
gameObject.GetComponent<Button>().onClick.AddListener(async () =>
{
void Awake() {
gameObject.GetComponent<Button>().onClick.AddListener(async () => {
await SceneManager.LoadSceneAsync(sceneName);
});
}
+3 -6
View File
@@ -1,14 +1,11 @@
using UnityEngine;
using UnityEngine.UI;
public class ButtonToURL : MonoBehaviour
{
public class ButtonToURL : MonoBehaviour {
[SerializeField] private string url;
void Awake()
{
gameObject.GetComponent<Button>().onClick.AddListener(() =>
{
void Awake() {
gameObject.GetComponent<Button>().onClick.AddListener(() => {
Application.OpenURL(url);
});
}
+58 -119
View File
@@ -12,8 +12,7 @@ using UnityEngine.Networking;
using UnityEngine.SceneManagement;
using UnityEngine.UI;
public class ChatroomMenu : MonoBehaviour
{
public class ChatroomMenu : MonoBehaviour {
[SerializeField] private TMP_Text statusText;
[SerializeField] private Button backButton;
[SerializeField] private Button sendButton;
@@ -39,89 +38,68 @@ public class ChatroomMenu : MonoBehaviour
[SerializeField] private Button reportMessagePanelSubmitButton;
[SerializeField] private TMP_InputField reportMessagePanelReportReason;
void Awake()
{
void Awake() {
messageInputField.onSelect.AddListener((_) => messageInputField.caretPosition = messageInputField.text.Length);
reportMessagePanelReportReason.onSelect.AddListener((_) => reportMessagePanelReportReason.caretPosition = reportMessagePanelReportReason.text.Length);
WebsocketHandler.Instance._Connection.StateChanged += OnStateChanged;
WebsocketHandler.Instance._Connection.MessageReceived += OnMessageReceived;
if (WebsocketHandler.Instance._Connection.State == WebSocketState.Connected)
{
if (WebsocketHandler.Instance._Connection.State == WebSocketState.Connected) {
statusText.text = "Loading messages";
RequestInfoMessage msg = new()
{
RequestInfoMessage msg = new() {
kind = "chatroom_messages"
};
WebsocketHandler.Instance._Connection.AddOutgoingMessage(JsonUtility.ToJson(msg));
}
}
private void OnStateChanged(WebSocketConnection connection, WebSocketState oldState, WebSocketState newState)
{
if (newState == WebSocketState.Connected)
{
private void OnStateChanged(WebSocketConnection connection, WebSocketState oldState, WebSocketState newState) {
if (newState == WebSocketState.Connected) {
statusText.text = "Loading messages";
RequestInfoMessage msg = new()
{
RequestInfoMessage msg = new() {
kind = "chatroom_messages"
};
WebsocketHandler.Instance._Connection.AddOutgoingMessage(JsonUtility.ToJson(msg));
}
}
private void OnMessageReceived(WebSocketConnection connection, WebSocketMessage message)
{
if (message.String != null && connection.State == WebSocketState.Connected)
{
private void OnMessageReceived(WebSocketConnection connection, WebSocketMessage message) {
if (message.String != null && connection.State == WebSocketState.Connected) {
JToken data = JToken.Parse(message.String);
if (data["for"] != null)
{
if (data["for"].ToString() == "info_request:chatroom_messages")
{
if (data["for"] != null) {
if (data["for"].ToString() == "info_request:chatroom_messages") {
var userId = BazookaManager.Instance.GetAccountID();
foreach (Transform item in content.transform)
{
foreach (Transform item in content.transform) {
if (!item.gameObject.activeSelf) continue;
Destroy(item.gameObject);
break;
}
foreach (var chatMessage in data["data"].ToObject<ChatroomMessage[]>())
{
foreach (var chatMessage in data["data"].ToObject<ChatroomMessage[]>()) {
InsertMessage(chatMessage, userId);
}
statusText.text = "";
StartCoroutine(ScrollToBottom());
CustomIconLoader.Init(FindObjectsByType<WaitingForCustomIcon>(FindObjectsSortMode.None));
}
else if (data["for"].ToString() == "upload:chatroom_message")
{
} else if (data["for"].ToString() == "upload:chatroom_message") {
var userId = BazookaManager.Instance.GetAccountID();
var chatMessage = data["data"].ToObject<ChatroomMessage>();
Destroy(content.transform.GetChild(1).gameObject);
InsertMessage(chatMessage, userId);
CustomIconLoader.Init(FindObjectsByType<WaitingForCustomIcon>(FindObjectsSortMode.None));
}
else if (data["for"].ToString() == "delete:chatroom_message")
{
} else if (data["for"].ToString() == "delete:chatroom_message") {
Destroy(content.transform.Find("ChatroomRow_" + data["data"]["id"].ToString() ?? "").gameObject);
if (data["data"]["fillerMessage"].ToString() != null)
{
if (data["data"]["fillerMessage"].ToString() != null) {
var userId = BazookaManager.Instance.GetAccountID();
var chatMessage = data["data"]["fillerMessage"].ToObject<ChatroomMessage>();
var row = InsertMessage(chatMessage, userId);
row.transform.SetSiblingIndex(1);
CustomIconLoader.Init(FindObjectsByType<WaitingForCustomIcon>(FindObjectsSortMode.None));
}
}
else if (data["for"].ToString() == "edit:chatroom_message")
{
if (data["data"]["newContent"].ToString() != null)
{
} else if (data["for"].ToString() == "edit:chatroom_message") {
if (data["data"]["newContent"].ToString() != null) {
var rowInfo = content.transform.Find("ChatroomRow_" + data["data"]["id"].ToString());
var usernameText = rowInfo.transform.GetChild(0).GetComponent<TMP_Text>();
if (!usernameText.text.EndsWith(">(edited)</color>"))
{
if (!usernameText.text.EndsWith(">(edited)</color>")) {
var color = BazookaManager.Instance.GetColorSettingText();
string hex = new Color((((float)color[0]) - 100f) / 255f, (((float)color[1]) - 100f) / 255f, (((float)color[2]) - 100f) / 255f).ToHexString();
rowInfo.transform.GetChild(0).GetComponent<TMP_Text>().text += $" <color=#{hex}>(edited)</color>";
@@ -133,8 +111,7 @@ public class ChatroomMenu : MonoBehaviour
}
}
GameObject InsertMessage(ChatroomMessage message, BigInteger? localUserId)
{
GameObject InsertMessage(ChatroomMessage message, BigInteger? localUserId) {
var obj = content.transform.Find("ChatroomRow_" + message.ID);
var rowInfo = Instantiate(sampleObject, content.transform);
@@ -152,8 +129,7 @@ public class ChatroomMenu : MonoBehaviour
usernameText.text = $"{message.Username} <color=#{hex1}>{Tools.FormatHumanTime(message.Timestamp)}</color>" + (message.EditedAt != 0 ? $" <color=#{hex2}>(edited)</color>" : null);
messageText.text = message.Content;
if (message.CustomIcon == null)
{
if (message.CustomIcon == null) {
playerIcon.sprite = Resources.Load<Sprite>("Icons/Icons/bird_" + message.Icon);
if (message.Icon == 1) playerIcon.sprite = Tools.GetIconForUser(message.UserID);
playerOverlayIcon.sprite = Resources.Load<Sprite>("Icons/Overlays/overlay_" + message.Overlay);
@@ -161,20 +137,16 @@ public class ChatroomMenu : MonoBehaviour
if (message.Overlay == 8) playerOverlayIcon.transform.localPosition = new UnityEngine.Vector2(-16.56f, 14.81f);
else if (message.Overlay == 11) playerOverlayIcon.transform.localPosition = new UnityEngine.Vector2(-14.74451f, 20.39122f);
else if (message.Overlay == 13) playerOverlayIcon.transform.localPosition = new UnityEngine.Vector2(-16.54019f, 14.70365f);
try
{
try {
playerIcon.color = new Color(message.BirdColor[0] / 255f, message.BirdColor[1] / 255f, message.BirdColor[2] / 255f);
playerOverlayIcon.color = new Color(message.OverlayColor[0] / 255f, message.OverlayColor[1] / 255f, message.OverlayColor[2] / 255f);
}
catch
{
catch {
playerIcon.color = Color.white;
playerOverlayIcon.color = Color.white;
}
}
else playerIcon.gameObject.AddComponent<WaitingForCustomIcon>().ID = message.CustomIcon;
playerIconButton.onClick.AddListener(async () =>
{
} else playerIcon.gameObject.AddComponent<WaitingForCustomIcon>().ID = message.CustomIcon;
playerIconButton.onClick.AddListener(async () => {
var clone = Instantiate(profilePrefab.gameObject, profilePrefab.gameObject.transform.parent);
clone.SetActive(true);
await clone.GetComponent<ProfileMenu>().Init(message.UserID);
@@ -187,17 +159,14 @@ public class ChatroomMenu : MonoBehaviour
return rowInfo;
}
void OnDestroy()
{
void OnDestroy() {
WebsocketHandler.Instance._Connection.StateChanged -= OnStateChanged;
WebsocketHandler.Instance._Connection.MessageReceived -= OnMessageReceived;
}
void Start()
{
void Start() {
reportMessagePanelReportReason.transform.GetChild(0).GetChild(1).GetComponent<TMP_Text>().textWrappingMode = TextWrappingModes.Normal;
if (BazookaManager.Instance.GetAccountID() == null || BazookaManager.Instance.GetAccountName() == null || BazookaManager.Instance.GetAccountSession() == null)
{
if (BazookaManager.Instance.GetAccountID() == null || BazookaManager.Instance.GetAccountName() == null || BazookaManager.Instance.GetAccountSession() == null) {
sendButton.interactable = false;
messageInputField.interactable = false;
}
@@ -206,15 +175,13 @@ public class ChatroomMenu : MonoBehaviour
messageInputField.textComponent.textWrappingMode = TextWrappingModes.Normal;
messageInputField.onSubmit.AddListener(_ => HandleMessageSubmit());
optionsPanelExitButton.onClick.AddListener(() =>
{
optionsPanelExitButton.onClick.AddListener(() => {
optionsPanel.SetActive(false);
selectedMessageForOptions = null;
});
optionsPanelDeleteButton.onClick.AddListener(() => { if (selectedMessageForOptions != null) HandleMessageDelete(); });
optionsPanelDeleteButton.onClick.AddListener(optionsPanelExitButton.onClick.Invoke);
optionsPanelEditButton.onClick.AddListener(() =>
{
optionsPanelEditButton.onClick.AddListener(() => {
var editMessage = Instantiate(editMessagePanelSample, editMessagePanelSample.transform.parent);
editMessagePanelCurrent = editMessage;
var editMessageChild = editMessage.transform.GetChild(0);
@@ -225,14 +192,12 @@ public class ChatroomMenu : MonoBehaviour
var editMessageChildNewContentInputBox = editMessageChild.GetChild(4).GetComponent<TMP_InputField>();
editMessageChildNewContentInputBox.onSelect.AddListener((_) => editMessageChildNewContentInputBox.caretPosition = editMessageChildNewContentInputBox.text.Length);
editMessageChildNewContentInputBox.text = selectedMessageForOptions.Content;
editMessageChildExitButton.onClick.AddListener(() =>
{
editMessageChildExitButton.onClick.AddListener(() => {
editMessagePanelCurrent = null;
Destroy(editMessage);
optionsPanel.SetActive(true);
});
editMessageChildSubmitButton.onClick.AddListener(() =>
{
editMessageChildSubmitButton.onClick.AddListener(() => {
HandleMessageEdit();
editMessagePanelCurrent = null;
Destroy(editMessage);
@@ -247,8 +212,7 @@ public class ChatroomMenu : MonoBehaviour
usernameText.text = selectedMessageForOptions.Username;
messageText.text = selectedMessageForOptions.Content;
if (selectedMessageForOptions.CustomIcon == null)
{
if (selectedMessageForOptions.CustomIcon == null) {
playerIcon.sprite = Resources.Load<Sprite>("Icons/Icons/bird_" + selectedMessageForOptions.Icon);
if (selectedMessageForOptions.Icon == 1) playerIcon.sprite = Tools.GetIconForUser(selectedMessageForOptions.UserID);
playerOverlayIcon.sprite = Resources.Load<Sprite>("Icons/Overlays/overlay_" + selectedMessageForOptions.Overlay);
@@ -256,18 +220,15 @@ public class ChatroomMenu : MonoBehaviour
if (selectedMessageForOptions.Overlay == 8) playerOverlayIcon.transform.localPosition = new UnityEngine.Vector2(-16.56f, 14.81f);
else if (selectedMessageForOptions.Overlay == 11) playerOverlayIcon.transform.localPosition = new UnityEngine.Vector2(-14.74451f, 20.39122f);
else if (selectedMessageForOptions.Overlay == 13) playerOverlayIcon.transform.localPosition = new UnityEngine.Vector2(-16.54019f, 14.70365f);
try
{
try {
playerIcon.color = new Color(selectedMessageForOptions.BirdColor[0] / 255f, selectedMessageForOptions.BirdColor[1] / 255f, selectedMessageForOptions.BirdColor[2] / 255f);
playerOverlayIcon.color = new Color(selectedMessageForOptions.OverlayColor[0] / 255f, selectedMessageForOptions.OverlayColor[1] / 255f, selectedMessageForOptions.OverlayColor[2] / 255f);
}
catch
{
catch {
playerIcon.color = Color.white;
playerOverlayIcon.color = Color.white;
}
}
else playerIcon.gameObject.AddComponent<WaitingForCustomIcon>().ID = selectedMessageForOptions.CustomIcon;
} else playerIcon.gameObject.AddComponent<WaitingForCustomIcon>().ID = selectedMessageForOptions.CustomIcon;
rowInfo = editMessageChild.GetChild(3);
usernameText = rowInfo.transform.GetChild(1).GetComponent<TMP_Text>();
@@ -278,8 +239,7 @@ public class ChatroomMenu : MonoBehaviour
usernameText.text = selectedMessageForOptions.Username;
messageText.text = selectedMessageForOptions.Content;
editMessageChildNewContentInputBox.onValueChanged.AddListener((value) => messageText.text = value);
if (selectedMessageForOptions.CustomIcon == null)
{
if (selectedMessageForOptions.CustomIcon == null) {
playerIcon.sprite = Resources.Load<Sprite>("Icons/Icons/bird_" + selectedMessageForOptions.Icon);
if (selectedMessageForOptions.Icon == 1) playerIcon.sprite = Tools.GetIconForUser(selectedMessageForOptions.UserID);
playerOverlayIcon.sprite = Resources.Load<Sprite>("Icons/Overlays/overlay_" + selectedMessageForOptions.Overlay);
@@ -287,61 +247,51 @@ public class ChatroomMenu : MonoBehaviour
if (selectedMessageForOptions.Overlay == 8) playerOverlayIcon.transform.localPosition = new UnityEngine.Vector2(-16.56f, 14.81f);
else if (selectedMessageForOptions.Overlay == 11) playerOverlayIcon.transform.localPosition = new UnityEngine.Vector2(-14.74451f, 20.39122f);
else if (selectedMessageForOptions.Overlay == 13) playerOverlayIcon.transform.localPosition = new UnityEngine.Vector2(-16.54019f, 14.70365f);
try
{
try {
playerIcon.color = new Color(selectedMessageForOptions.BirdColor[0] / 255f, selectedMessageForOptions.BirdColor[1] / 255f, selectedMessageForOptions.BirdColor[2] / 255f);
playerOverlayIcon.color = new Color(selectedMessageForOptions.OverlayColor[0] / 255f, selectedMessageForOptions.OverlayColor[1] / 255f, selectedMessageForOptions.OverlayColor[2] / 255f);
}
catch
{
catch {
playerIcon.color = Color.white;
playerOverlayIcon.color = Color.white;
}
}
else playerIcon.gameObject.AddComponent<WaitingForCustomIcon>().ID = selectedMessageForOptions.CustomIcon;
} else playerIcon.gameObject.AddComponent<WaitingForCustomIcon>().ID = selectedMessageForOptions.CustomIcon;
optionsPanel.SetActive(false);
editMessage.SetActive(true);
CustomIconLoader.Init(FindObjectsByType<WaitingForCustomIcon>(FindObjectsSortMode.None));
});
optionsPanelReportButton.onClick.AddListener(() =>
{
optionsPanelReportButton.onClick.AddListener(() => {
reportMessagePanelReportReason.text = "";
optionsPanel.SetActive(false);
reportMessagePanel.SetActive(true);
});
reportMessagePanelExitButton.onClick.AddListener(() =>
{
reportMessagePanelExitButton.onClick.AddListener(() => {
editMessagePanelCurrent = null;
reportMessagePanel.SetActive(false);
optionsPanel.SetActive(true);
});
reportMessagePanelSubmitButton.onClick.AddListener(async () =>
{
reportMessagePanelSubmitButton.onClick.AddListener(async () => {
reportMessagePanel.SetActive(false);
await HandleMessageReport();
editMessagePanelCurrent = null;
selectedMessageForOptions = null;
});
optionsPanelCopyButton.onClick.AddListener(() =>
{
optionsPanelCopyButton.onClick.AddListener(() => {
if (selectedMessageForOptions != null) GUIUtility.systemCopyBuffer = selectedMessageForOptions.Content;
});
optionsPanelCopyButton.onClick.AddListener(optionsPanelExitButton.onClick.Invoke);
}
void HandleMessageSubmit()
{
void HandleMessageSubmit() {
if (messageInputField.text.Trim() == string.Empty) return;
sendButton.interactable = false;
backButton.interactable = false;
messageInputField.interactable = false;
UploadMessage msg = new()
{
UploadMessage msg = new() {
kind = "chatroom_message",
data = new JObject()
{
data = new JObject() {
["content"] = messageInputField.text,
["auth"] = BazookaManager.Instance.GetAccountSession()
}
@@ -354,13 +304,10 @@ public class ChatroomMenu : MonoBehaviour
StartCoroutine(ScrollToBottom());
}
void HandleMessageDelete()
{
DeleteMessage msg = new()
{
void HandleMessageDelete() {
DeleteMessage msg = new() {
kind = "chatroom_message",
data = new JObject()
{
data = new JObject() {
["id"] = (int)selectedMessageForOptions.ID,
["auth"] = BazookaManager.Instance.GetAccountSession()
}
@@ -369,15 +316,12 @@ public class ChatroomMenu : MonoBehaviour
StartCoroutine(ScrollToBottom());
}
void HandleMessageEdit()
{
void HandleMessageEdit() {
var newContent = editMessagePanelCurrent.transform.GetChild(0).GetChild(4).GetComponent<TMP_InputField>().text;
selectedMessageForOptions.Content = newContent;
EditMessage msg = new()
{
EditMessage msg = new() {
kind = "chatroom_message",
data = new JObject()
{
data = new JObject() {
["id"] = (int)selectedMessageForOptions.ID,
["newContent"] = newContent,
["auth"] = BazookaManager.Instance.GetAccountSession()
@@ -387,8 +331,7 @@ public class ChatroomMenu : MonoBehaviour
StartCoroutine(ScrollToBottom());
}
async Task HandleMessageReport()
{
async Task HandleMessageReport() {
WWWForm dataForm = new();
dataForm.AddField("id", selectedMessageForOptions.ID.ToString());
dataForm.AddField("reason", reportMessagePanelReportReason.text);
@@ -401,13 +344,11 @@ public class ChatroomMenu : MonoBehaviour
StartCoroutine(ScrollToBottom());
}
async void Update()
{
async void Update() {
var max = content.GetComponent<RectTransform>().sizeDelta.y;
var current = content.transform.localPosition.y;
downButton.gameObject.SetActive(Mathf.Abs(max - current) > 0.1f * max);
if (Keyboard.current.escapeKey.wasPressedThisFrame && FindFirstObjectByType<ProfileMenu>() == null)
{
if (Keyboard.current.escapeKey.wasPressedThisFrame && FindFirstObjectByType<ProfileMenu>() == null) {
if (optionsPanel.activeSelf) optionsPanelExitButton.onClick.Invoke();
else if (reportMessagePanel.activeSelf) reportMessagePanelExitButton.onClick.Invoke();
else if (editMessagePanelCurrent != null) editMessagePanelCurrent.transform.GetChild(0).GetChild(0).GetComponent<Button>().onClick.Invoke();
@@ -415,14 +356,12 @@ public class ChatroomMenu : MonoBehaviour
}
}
IEnumerator ScrollToBottom()
{
IEnumerator ScrollToBottom() {
yield return new WaitForEndOfFrame();
content.transform.localPosition = new UnityEngine.Vector2(0f, content.GetComponent<RectTransform>().sizeDelta.y);
}
void OptionsButtonClick(ChatroomMessage message, BigInteger localUserId)
{
void OptionsButtonClick(ChatroomMessage message, BigInteger localUserId) {
selectedMessageForOptions = message;
optionsPanelDeleteButton.transform.parent.gameObject.SetActive(localUserId != 0 && message.UserID == localUserId);
optionsPanelEditButton.transform.parent.gameObject.SetActive(localUserId != 0 && message.UserID == localUserId);
+18 -38
View File
@@ -2,82 +2,62 @@ using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.UI;
public class ChatroomMenuEntry : MonoBehaviour, IPointerEnterHandler, IPointerExitHandler, IPointerClickHandler
{
public class ChatroomMenuEntry : MonoBehaviour, IPointerEnterHandler, IPointerExitHandler, IPointerClickHandler {
private Button optionsButton;
private static ChatroomMenuEntry activeEntry;
public void Init(Button optionsButtonArg)
{
public void Init(Button optionsButtonArg) {
optionsButton = optionsButtonArg;
var color = BazookaManager.Instance.GetColorSettingMenuBackground();
gameObject.GetComponent<Image>().color = new Color((((float)color[0]) + 24f) / 255f, (((float)color[1]) + 24f) / 255f, (((float)color[2]) + 24f) / 255f);
optionsButton.gameObject.SetActive(false);
}
public void OnPointerEnter(PointerEventData e)
{
if (!Application.isMobilePlatform)
{
if (activeEntry != null && activeEntry != this)
{
public void OnPointerEnter(PointerEventData e) {
if (!Application.isMobilePlatform) {
if (activeEntry != null && activeEntry != this) {
activeEntry.Deactivate();
}
if (activeEntry != this)
{
if (activeEntry != this) {
Activate();
}
}
}
public void OnPointerExit(PointerEventData e)
{
if (!Application.isMobilePlatform)
{
if (activeEntry != null && activeEntry != this)
{
public void OnPointerExit(PointerEventData e) {
if (!Application.isMobilePlatform) {
if (activeEntry != null && activeEntry != this) {
activeEntry.Deactivate();
}
if (activeEntry == this)
{
if (activeEntry == this) {
Deactivate();
}
}
}
public void OnPointerClick(PointerEventData e)
{
if (Application.isMobilePlatform)
{
if (activeEntry != null && activeEntry != this)
{
public void OnPointerClick(PointerEventData e) {
if (Application.isMobilePlatform) {
if (activeEntry != null && activeEntry != this) {
activeEntry.Deactivate();
}
if (activeEntry == this)
{
if (activeEntry == this) {
Deactivate();
}
else
{
} else {
Activate();
}
}
else if (e.button == PointerEventData.InputButton.Right)
{
} else if (e.button == PointerEventData.InputButton.Right) {
optionsButton.onClick?.Invoke();
}
}
private void Activate()
{
private void Activate() {
activeEntry = this;
var color = BazookaManager.Instance.GetColorSettingMenuBackground();
gameObject.GetComponent<Image>().color = new Color((((float)color[0]) + 36f) / 255f, (((float)color[1]) + 36f) / 255f, (((float)color[2]) + 36f) / 255f);
optionsButton.gameObject.SetActive(true);
}
private void Deactivate()
{
private void Deactivate() {
var color = BazookaManager.Instance.GetColorSettingMenuBackground();
gameObject.GetComponent<Image>().color = new Color((((float)color[0]) + 24f) / 255f, (((float)color[1]) + 24f) / 255f, (((float)color[2]) + 24f) / 255f);
optionsButton.gameObject.SetActive(false);
+12 -24
View File
@@ -4,8 +4,7 @@ using TMPro;
using UnityEngine;
using UnityEngine.UI;
public class ColorPanel : MonoBehaviour
{
public class ColorPanel : MonoBehaviour {
public Slider rSlider;
public Slider gSlider;
public Slider bSlider;
@@ -18,13 +17,11 @@ public class ColorPanel : MonoBehaviour
public event Action<JArray> OnColorChanged;
public Color defaultColor;
void Awake()
{
void Awake() {
hexValue.onSelect.AddListener((_) => hexValue.caretPosition = hexValue.text.Length);
}
public void Init(Color color, Color defaultColorArg)
{
public void Init(Color color, Color defaultColorArg) {
defaultColor = defaultColorArg;
rSlider.value = color.r * 255f;
gSlider.value = color.g * 255f;
@@ -36,11 +33,9 @@ public class ColorPanel : MonoBehaviour
gSlider.onValueChanged.AddListener(_ => SyncAll());
bSlider.onValueChanged.AddListener(_ => SyncAll());
hexValue.onValueChanged.AddListener(value =>
{
hexValue.onValueChanged.AddListener(value => {
var hex = value.StartsWith("#") ? value : "#" + value;
if (hex.Length == 7 && ColorUtility.TryParseHtmlString(hex, out var col))
{
if (hex.Length == 7 && ColorUtility.TryParseHtmlString(hex, out var col)) {
rSlider.SetValueWithoutNotify(col.r * 255f);
gSlider.SetValueWithoutNotify(col.g * 255f);
bSlider.SetValueWithoutNotify(col.b * 255f);
@@ -48,22 +43,19 @@ public class ColorPanel : MonoBehaviour
}
});
resetButton.onClick.AddListener(() =>
{
resetButton.onClick.AddListener(() => {
rSlider.value = defaultColor.r * 255f;
gSlider.value = defaultColor.g * 255f;
bSlider.value = defaultColor.b * 255f;
});
switchModeButton.onClick.AddListener(() =>
{
switchModeButton.onClick.AddListener(() => {
bool enableManual = !manualModeUI.activeSelf;
manualModeUI.SetActive(enableManual);
colorPickerUI.gameObject.SetActive(!enableManual);
});
colorPickerUI.OnColorChanged += color =>
{
colorPickerUI.OnColorChanged += color => {
rSlider.SetValueWithoutNotify(color.r * 255);
gSlider.SetValueWithoutNotify(color.g * 255);
bSlider.SetValueWithoutNotify(color.b * 255);
@@ -71,14 +63,12 @@ public class ColorPanel : MonoBehaviour
};
}
public void Init(JArray color, Color defaultColorArg)
{
public void Init(JArray color, Color defaultColorArg) {
Init(new Color((int)color[0] / 255f, (int)color[1] / 255f, (int)color[2] / 255f), defaultColorArg);
}
void SyncAll(bool fromPicker = false)
{
void SyncAll(bool fromPicker = false) {
var col = new Color(rSlider.value / 255f, gSlider.value / 255f, bSlider.value / 255f);
if (!fromPicker) colorPickerUI.SetSelectedColor(rSlider.value, gSlider.value, bSlider.value);
@@ -92,16 +82,14 @@ public class ColorPanel : MonoBehaviour
));
}
public void SetColor(Color col)
{
public void SetColor(Color col) {
rSlider.SetValueWithoutNotify(col.r * 255f);
gSlider.SetValueWithoutNotify(col.g * 255f);
bSlider.SetValueWithoutNotify(col.b * 255f);
SyncAll();
}
public void SetColor(JArray color)
{
public void SetColor(JArray color) {
rSlider.SetValueWithoutNotify((int)color[0]);
gSlider.SetValueWithoutNotify((int)color[1]);
bSlider.SetValueWithoutNotify((int)color[2]);
+23 -48
View File
@@ -3,8 +3,7 @@ using UnityEngine;
using UnityEngine.InputSystem;
using UnityEngine.UI;
public class ColorPickerUI : MonoBehaviour
{
public class ColorPickerUI : MonoBehaviour {
public RawImage hueImage;
public RawImage svImage;
public RectTransform svCursor;
@@ -26,8 +25,7 @@ public class ColorPickerUI : MonoBehaviour
private Color lastColor;
void Start()
{
void Start() {
GenerateHueBar();
GenerateSVBox(selectedHue);
UpdateSVCursor();
@@ -36,46 +34,39 @@ public class ColorPickerUI : MonoBehaviour
OnColorChanged?.Invoke(lastColor);
}
void Update()
{
void Update() {
if (Pointer.current == null)
return;
bool pressed = Pointer.current.press.isPressed;
Vector2 mousePos = Pointer.current.position.ReadValue();
if (pressed && currentDrag == DragTarget.None)
{
if (pressed && currentDrag == DragTarget.None) {
if (RectTransformUtility.RectangleContainsScreenPoint(hueImage.rectTransform, mousePos, null))
currentDrag = DragTarget.Hue;
else if (RectTransformUtility.RectangleContainsScreenPoint(svImage.rectTransform, mousePos, null))
currentDrag = DragTarget.SV;
}
if (!pressed)
{
if (!pressed) {
currentDrag = DragTarget.None;
return;
}
bool colorChanged = false;
if (currentDrag == DragTarget.Hue)
{
if (currentDrag == DragTarget.Hue) {
RectTransformUtility.ScreenPointToLocalPointInRectangle(hueImage.rectTransform, mousePos, null, out Vector2 localPoint);
float y = Mathf.Clamp01((localPoint.y + hueImage.rectTransform.rect.height / 2f) / hueImage.rectTransform.rect.height);
float newHue = 1f - y;
if (!Mathf.Approximately(newHue, selectedHue))
{
if (!Mathf.Approximately(newHue, selectedHue)) {
selectedHue = newHue;
GenerateSVBox(selectedHue);
UpdateSVCursor();
UpdateHueCursor();
colorChanged = true;
}
}
else if (currentDrag == DragTarget.SV)
{
} else if (currentDrag == DragTarget.SV) {
RectTransformUtility.ScreenPointToLocalPointInRectangle(svImage.rectTransform, mousePos, null, out Vector2 localPoint);
float rectWidth = svImage.rectTransform.rect.width;
float rectHeight = svImage.rectTransform.rect.height;
@@ -83,8 +74,7 @@ public class ColorPickerUI : MonoBehaviour
float y = (localPoint.y + rectHeight / 2f) / rectHeight;
float newS = Mathf.Clamp01(x);
float newV = Mathf.Clamp01(y);
if (!Mathf.Approximately(newS, selectedS) || !Mathf.Approximately(newV, selectedV))
{
if (!Mathf.Approximately(newS, selectedS) || !Mathf.Approximately(newV, selectedV)) {
selectedS = newS;
selectedV = newV;
UpdateSVCursor();
@@ -92,19 +82,16 @@ public class ColorPickerUI : MonoBehaviour
}
}
if (colorChanged)
{
if (colorChanged) {
Color currentColor = GetSelectedColor();
if (currentColor != lastColor)
{
if (currentColor != lastColor) {
lastColor = currentColor;
OnColorChanged?.Invoke(currentColor);
}
}
}
void UpdateSVCursor()
{
void UpdateSVCursor() {
if (svCursor == null) return;
Rect rect = svImage.rectTransform.rect;
float x = selectedS * rect.width;
@@ -115,8 +102,7 @@ public class ColorPickerUI : MonoBehaviour
svCursor.anchoredPosition = clampedPos;
}
void UpdateHueCursor()
{
void UpdateHueCursor() {
if (hueCursor == null) return;
Rect rect = hueImage.rectTransform.rect;
float y = (1f - selectedHue) * rect.height;
@@ -125,12 +111,10 @@ public class ColorPickerUI : MonoBehaviour
hueCursor.anchoredPosition = pos;
}
void GenerateHueBar()
{
void GenerateHueBar() {
hueTexture = new Texture2D(1, hueHeight);
hueTexture.wrapMode = TextureWrapMode.Clamp;
for (int y = 0; y < hueHeight; y++)
{
for (int y = 0; y < hueHeight; y++) {
float h = 1f - (float)y / (hueHeight - 1);
Color color = Color.HSVToRGB(h, 1f, 1f);
hueTexture.SetPixel(0, y, color);
@@ -139,15 +123,12 @@ public class ColorPickerUI : MonoBehaviour
hueImage.texture = hueTexture;
}
void GenerateSVBox(float hue)
{
void GenerateSVBox(float hue) {
svTexture = new Texture2D(svSize, svSize);
svTexture.wrapMode = TextureWrapMode.Clamp;
for (int y = 0; y < svSize; y++)
{
for (int y = 0; y < svSize; y++) {
float v = (float)y / (svSize - 1);
for (int x = 0; x < svSize; x++)
{
for (int x = 0; x < svSize; x++) {
float s = (float)x / (svSize - 1);
Color color = Color.HSVToRGB(hue, s, v);
svTexture.SetPixel(x, y, color);
@@ -157,22 +138,17 @@ public class ColorPickerUI : MonoBehaviour
svImage.texture = svTexture;
}
public Color GetSelectedColor()
{
public Color GetSelectedColor() {
return Color.HSVToRGB(selectedHue, selectedS, selectedV);
}
public void SetSelectedColor(float r, float g, float b)
{
public void SetSelectedColor(float r, float g, float b) {
Color32 color = new((byte)r, (byte)g, (byte)b, 255);
if (color.r == 0 && color.g == 0 && color.b == 0)
{
if (color.r == 0 && color.g == 0 && color.b == 0) {
selectedS = 0;
selectedV = 0;
}
else
{
} else {
Color.RGBToHSV(color, out float h, out float s, out float v);
selectedHue = h;
selectedS = s;
@@ -184,8 +160,7 @@ public class ColorPickerUI : MonoBehaviour
UpdateHueCursor();
var current = GetSelectedColor();
if (current != lastColor)
{
if (current != lastColor) {
lastColor = current;
OnColorChanged?.Invoke(current);
}
+7 -15
View File
@@ -3,25 +3,20 @@ using TMPro;
using UnityEngine;
using UnityEngine.UI;
public class CustomColorObject : MonoBehaviour
{
public class CustomColorObject : MonoBehaviour {
[SerializeField] private ColorObjectType type;
[SerializeField] private bool invert;
[SerializeField] private Color addMore;
[SerializeField] private bool reverseAdd;
Color ApplyModifiers(Color baseColor)
{
Color ApplyModifiers(Color baseColor) {
if (invert) baseColor = new(1f - baseColor.r, 1f - baseColor.g, 1f - baseColor.b);
if (reverseAdd)
{
if (reverseAdd) {
baseColor.r = Mathf.Clamp01(baseColor.r - addMore.r);
baseColor.g = Mathf.Clamp01(baseColor.g - addMore.g);
baseColor.b = Mathf.Clamp01(baseColor.b - addMore.b);
}
else
{
} else {
baseColor.r = Mathf.Clamp01(baseColor.r + addMore.r);
baseColor.g = Mathf.Clamp01(baseColor.g + addMore.g);
baseColor.b = Mathf.Clamp01(baseColor.b + addMore.b);
@@ -30,14 +25,12 @@ public class CustomColorObject : MonoBehaviour
return baseColor;
}
public void SetColor()
{
public void SetColor() {
JArray color = null;
Color colorType = Color.white;
Color currentColor = Color.white;
switch (type)
{
switch (type) {
case ColorObjectType.InGameBackgroundColor:
color = BazookaManager.Instance.GetColorSettingBackground();
colorType = new((int)color[0] / 255f, (int)color[1] / 255f, (int)color[2] / 255f);
@@ -151,8 +144,7 @@ public class CustomColorObject : MonoBehaviour
}
}
void Start()
{
void Start() {
SetColor();
}
}
+135 -303
View File
@@ -1,4 +1,4 @@
using System.Linq;
using System.Linq;
using System.Numerics;
using TMPro;
using UnityEngine;
@@ -6,8 +6,7 @@ using UnityEngine.InputSystem;
using UnityEngine.SceneManagement;
using UnityEngine.UI;
public class CustomGamePlayer : MonoBehaviour
{
public class CustomGamePlayer : MonoBehaviour {
public static CustomGamePlayer instance;
private readonly float spawnRate = 1f;
private float nextSpawnTime;
@@ -46,11 +45,9 @@ public class CustomGamePlayer : MonoBehaviour
private float goldenBerryChance;
private float nothingBerryChance;
void Start()
{
void Start() {
CustomGameTempData customGameTempData = FindObjectsByType<CustomGameTempData>(FindObjectsSortMode.None)[0];
if (customGameTempData == null)
{
if (customGameTempData == null) {
SceneManager.LoadScene("MainMenu");
return;
}
@@ -74,8 +71,7 @@ public class CustomGamePlayer : MonoBehaviour
var customIconData = BazookaManager.Instance.GetCustomBirdIconData();
SpriteRenderer birdRender = bird.GetComponent<SpriteRenderer>();
if (customIconData.Selected == null)
{
if (customIconData.Selected == null) {
var birdColor = BazookaManager.Instance.GetColorSettingIcon();
var overlayColor = BazookaManager.Instance.GetColorSettingOverlay();
bird.GetComponent<SpriteRenderer>().color = new Color(
@@ -91,49 +87,35 @@ public class CustomGamePlayer : MonoBehaviour
int icon = BazookaManager.Instance.GetBirdIcon();
int iconOverlay = BazookaManager.Instance.GetBirdOverlay();
if (icon == 1)
{
if (icon == 1) {
birdRender.sprite = Tools.GetIconForUser(BazookaManager.Instance.GetAccountID() ?? 0);
}
else
{
} else {
birdRender.sprite = Resources.Load<Sprite>("Icons/Icons/bird_" + icon);
}
if (iconOverlay == 8)
{
if (iconOverlay == 8) {
overlayRender.sprite = Resources.Load<Sprite>("Icons/Overlays/overlay_" + iconOverlay);
overlayRender.transform.localPosition = new UnityEngine.Vector3(-0.37f, 0.32f, 0f);
}
else if (iconOverlay == 11)
{
} else if (iconOverlay == 11) {
overlayRender.sprite = Resources.Load<Sprite>("Icons/Overlays/overlay_" + iconOverlay);
overlayRender.transform.localScale = new UnityEngine.Vector3(1.1f, 1.1f, 1.1f); //yea i didnt feel like doing it for all lmao
overlayRender.transform.localPosition = new UnityEngine.Vector3(-0.3141809f, 0.4324968f, 0f);
}
else if (iconOverlay == 13)
{
} else if (iconOverlay == 13) {
overlayRender.sprite = Resources.Load<Sprite>("Icons/Overlays/overlay_" + iconOverlay);
overlayRender.transform.localPosition = new UnityEngine.Vector3(-0.3559977f, 0.3179995f, 0f);
}
else
{
} else {
overlayRender.sprite = Resources.Load<Sprite>("Icons/Overlays/overlay_" + iconOverlay);
}
if (birdRender.sprite == null)
{
if (birdRender.sprite == null) {
birdRender.sprite = Resources.Load<Sprite>("Icons/Icons/bird_1");
BazookaManager.Instance.SetBirdIcon(1);
}
if (overlayRender.sprite == null && iconOverlay != 0)
{
if (overlayRender.sprite == null && iconOverlay != 0) {
overlayRender.sprite = Resources.Load<Sprite>("Icons/Overlays/overlay_1");
BazookaManager.Instance.SetBirdOverlay(1);
}
}
else if (customIconData.Selected != null)
} else if (customIconData.Selected != null)
foreach (var icon in customIconData.Purchased)
if (icon == customIconData.Selected)
{
if (icon == customIconData.Selected) {
var waitingForCustomIcon = birdRender.gameObject.AddComponent<WaitingForCustomIcon>();
waitingForCustomIcon.ID = customIconData.Selected;
CustomIconLoader.Init(new[] { waitingForCustomIcon });
@@ -151,8 +133,7 @@ public class CustomGamePlayer : MonoBehaviour
UpdateStats(0);
}
void MoveBird()
{
void MoveBird() {
float screenWidth = Camera.main.orthographicSize * 2f * Camera.main.aspect;
float baseSpeed = 0.18f * (screenWidth / 20.19257f);
bool doMoveRight = false;
@@ -161,42 +142,31 @@ public class CustomGamePlayer : MonoBehaviour
bool doRestart = false;
bool doBack = false;
float movespeed = baseSpeed;
if (boostLeft > 0f || speedyLeft > 0f)
{
if (boostLeft > 0f || speedyLeft > 0f) {
movespeed = baseSpeed * 1.39f;
}
else if (slownessLeft > 0f)
{
} else if (slownessLeft > 0f) {
movespeed = baseSpeed * 0.56f;
}
CheckIfGrounded();
bool controllerLeft = Gamepad.current != null && (Gamepad.current.leftStick.left.isPressed || Gamepad.current.dpad.left.isPressed || Gamepad.current.rightStick.left.isPressed);
bool controllerRight = Gamepad.current != null && (Gamepad.current.leftStick.right.isPressed || Gamepad.current.dpad.right.isPressed || Gamepad.current.rightStick.right.isPressed);
bool controllerJump = Gamepad.current != null && (Gamepad.current.leftStick.up.isPressed || Gamepad.current.leftStick.down.isPressed || Gamepad.current.dpad.up.isPressed || Gamepad.current.dpad.down.isPressed || Gamepad.current.rightStick.up.isPressed || Gamepad.current.rightStick.down.isPressed);
if (!Application.isMobilePlatform)
{
if (controllerLeft || Keyboard.current.leftArrowKey.isPressed || Keyboard.current.aKey.isPressed || Keyboard.current.jKey.isPressed)
{
if (!Application.isMobilePlatform) {
if (controllerLeft || Keyboard.current.leftArrowKey.isPressed || Keyboard.current.aKey.isPressed || Keyboard.current.jKey.isPressed) {
doMoveLeft = true;
}
if (controllerRight || Keyboard.current.rightArrowKey.isPressed || Keyboard.current.dKey.isPressed || Keyboard.current.lKey.isPressed)
{
if (controllerRight || Keyboard.current.rightArrowKey.isPressed || Keyboard.current.dKey.isPressed || Keyboard.current.lKey.isPressed) {
doMoveRight = true;
}
if (controllerJump || Keyboard.current.spaceKey.isPressed || Keyboard.current.upArrowKey.isPressed || Keyboard.current.wKey.isPressed || Keyboard.current.downArrowKey.isPressed || Keyboard.current.sKey.isPressed || Keyboard.current.kKey.isPressed || Keyboard.current.iKey.isPressed || Mouse.current.leftButton.isPressed || (Gamepad.current != null && Gamepad.current.buttonSouth.isPressed))
{
if (controllerJump || Keyboard.current.spaceKey.isPressed || Keyboard.current.upArrowKey.isPressed || Keyboard.current.wKey.isPressed || Keyboard.current.downArrowKey.isPressed || Keyboard.current.sKey.isPressed || Keyboard.current.kKey.isPressed || Keyboard.current.iKey.isPressed || Mouse.current.leftButton.isPressed || (Gamepad.current != null && Gamepad.current.buttonSouth.isPressed)) {
doJump = true;
}
if (Keyboard.current.rKey.isPressed)
{
if (Keyboard.current.rKey.isPressed) {
doRestart = true;
}
}
else
{
} else {
var touches = UnityEngine.InputSystem.EnhancedTouch.Touch.activeTouches;
for (int i = 0; i < touches.Count; i++)
{
for (int i = 0; i < touches.Count; i++) {
var pos = touches[i].screenPosition;
UnityEngine.Vector3 clickPosition = Camera.main.ScreenToWorldPoint(new UnityEngine.Vector3(pos.x, pos.y, 0f));
clickPosition.z = 0f;
@@ -207,56 +177,42 @@ public class CustomGamePlayer : MonoBehaviour
if (pauseButton.GetComponent<HoldableButton>().isPressed) doBack = true;
}
}
if (doMoveLeft && !doMoveRight)
{
if (doMoveLeft && !doMoveRight) {
lastMoveTime = Time.time;
bird.transform.position += new UnityEngine.Vector3(-movespeed, 0f, 0f);
ClampPosition(bird);
bird.transform.localScale = new UnityEngine.Vector3(1.35f, 1.35f, 1.35f);
}
if (doMoveRight && !doMoveLeft)
{
if (doMoveRight && !doMoveLeft) {
lastMoveTime = Time.time;
bird.transform.position += new UnityEngine.Vector3(movespeed, 0f, 0f);
ClampPosition(bird);
bird.transform.localScale = new UnityEngine.Vector3(-1.35f, 1.35f, 1.35f);
}
if (doJump && isGrounded)
{
if (doJump && isGrounded) {
lastMoveTime = Time.time;
AudioSource.PlayClipAtPoint(Resources.Load<AudioClip>("Sounds/Jump"), Camera.main.transform.position, 0.75f * BazookaManager.Instance.GetSettingSFXVolume());
if (boostLeft > 0f || speedyLeft > 0f)
{
if (boostLeft > 0f || speedyLeft > 0f) {
rb.linearVelocity = UnityEngine.Vector2.up * 12f;
}
else if (slownessLeft > 0f)
{
} else if (slownessLeft > 0f) {
rb.linearVelocity = UnityEngine.Vector2.up * 6f;
}
else
{
} else {
rb.linearVelocity = UnityEngine.Vector2.up * 9f;
}
}
if (doBack)
{
if (doBack) {
TogglePause();
}
if (doRestart)
{
if (doRestart) {
if (score != 0) Respawn();
}
if (antiLeft > 0f || goldenLeft > 0f)
{
if (antiLeft > 0f || goldenLeft > 0f) {
string[] berryTags = { "NormalBerry", "SlowBerry", "UltraBerry", "SpeedyBerry", "CoinBerry", "RandomBerry", "AntiBerry", "GoldenBerry" };
if (antiLeft > 0f) berryTags.Append("PoisonBerry");
foreach (string tag in berryTags)
{
foreach (var berry in GameObject.FindGameObjectsWithTag(tag))
{
foreach (string tag in berryTags) {
foreach (var berry in GameObject.FindGameObjectsWithTag(tag)) {
UnityEngine.Vector3 dir = berry.transform.position - bird.transform.position;
if (dir.magnitude < (antiLeft > 0 ? 3f : 4.5f))
{
if (dir.magnitude < (antiLeft > 0 ? 3f : 4.5f)) {
berry.GetComponent<Rigidbody2D>().linearVelocity = dir.normalized * (antiLeft > 0 ? 5f : -5f);
ClampPosition(berry, false);
}
@@ -265,8 +221,7 @@ public class CustomGamePlayer : MonoBehaviour
}
}
void ClampPosition(GameObject obj, bool modifyY = true)
{
void ClampPosition(GameObject obj, bool modifyY = true) {
var cam = Camera.main;
var pos = obj.transform.position;
var bounds = obj.GetComponent<Renderer>().bounds.extents;
@@ -282,103 +237,78 @@ public class CustomGamePlayer : MonoBehaviour
obj.transform.position = pos;
}
void FixedUpdate()
{
void FixedUpdate() {
SpawnBerries();
if (!pausePanel.activeSelf)
{
if (!pausePanel.activeSelf) {
MoveBird();
if (boostLeft > 0f)
{
if (boostLeft > 0f) {
boostLeft -= Time.deltaTime;
boostText.text = "Boost expires in " + string.Format("{0:0.0}", boostLeft) + "s";
}
else if (slownessLeft > 0f)
{
} else if (slownessLeft > 0f) {
slownessLeft -= Time.deltaTime;
boostText.text = "Slowness expires in " + string.Format("{0:0.0}", slownessLeft) + "s";
}
else if (speedyLeft > 0f)
{
} else if (speedyLeft > 0f) {
speedyLeft -= Time.deltaTime;
boostText.text = "Speed expires in " + string.Format("{0:0.0}", speedyLeft) + "s";
}
else if (antiLeft > 0f)
{
} else if (antiLeft > 0f) {
antiLeft -= Time.deltaTime;
boostText.text = "Berry repellent expires in " + string.Format("{0:0.0}", antiLeft) + "s";
}
else if (goldenLeft > 0f)
{
} else if (goldenLeft > 0f) {
goldenLeft -= Time.deltaTime;
boostText.text = "Berry magnet expires in " + string.Format("{0:0.0}", goldenLeft) + "s";
}
else
{
} else {
boostText.text = "";
}
}
}
void SpawnBerries()
{
if (Time.time < nextSpawnTime)
{
void SpawnBerries() {
if (Time.time < nextSpawnTime) {
return;
}
if (speedyLeft > 0)
{
if (speedyLeft > 0) {
nextSpawnTime = Time.time + 1f / (spawnRate * 1.875f);
}
else
{
} else {
nextSpawnTime = Time.time + 1f / spawnRate;
}
float spawnProbability = Random.value;
if (!pausePanel.activeSelf)
{
if (!pausePanel.activeSelf) {
float cumulative = 0f;
GameObject newBerry = new("Berry");
newBerry.transform.SetParent(berryParent.transform);
SpriteRenderer spriteRenderer = newBerry.AddComponent<SpriteRenderer>();
cumulative += normalBerryChance / 100f;
if (spawnProbability <= cumulative)
{
if (spawnProbability <= cumulative) {
spriteRenderer.sprite = Resources.Load<Sprite>("Berries/Berry");
newBerry.tag = "NormalBerry";
goto finish;
}
cumulative += poisonBerryChance / 100f;
if (spawnProbability <= cumulative)
{
if (spawnProbability <= cumulative) {
spriteRenderer.sprite = Resources.Load<Sprite>("Berries/PoisonBerry");
newBerry.tag = "PoisonBerry";
goto finish;
}
cumulative += slowBerryChance / 100f;
if (spawnProbability <= cumulative)
{
if (spawnProbability <= cumulative) {
spriteRenderer.sprite = Resources.Load<Sprite>("Berries/SlowBerry");
newBerry.tag = "SlowBerry";
goto finish;
}
cumulative += ultraBerryChance / 100f;
if (spawnProbability <= cumulative)
{
if (spawnProbability <= cumulative) {
spriteRenderer.sprite = Resources.Load<Sprite>("Berries/UltraBerry");
newBerry.tag = "UltraBerry";
goto finish;
}
cumulative += speedyBerryChance / 100f;
if (spawnProbability <= cumulative)
{
if (spawnProbability <= cumulative) {
spriteRenderer.sprite = Resources.Load<Sprite>("Berries/SpeedyBerry");
newBerry.tag = "SpeedyBerry";
goto finish;
}
cumulative += randomBerryChance / 100f;
if (spawnProbability <= cumulative)
{
if (spawnProbability <= cumulative) {
spriteRenderer.sprite = Resources.Load<Sprite>("Berries/BerryNoColor");
newBerry.tag = "RandomBerry";
RainbowSpriteRender randomBerryRainbowImage = newBerry.AddComponent<RainbowSpriteRender>();
@@ -386,22 +316,19 @@ public class CustomGamePlayer : MonoBehaviour
goto finish;
}
cumulative += antiBerryChance / 100f;
if (spawnProbability <= cumulative)
{
if (spawnProbability <= cumulative) {
spriteRenderer.sprite = Resources.Load<Sprite>("Berries/AntiBerry");
newBerry.tag = "AntiBerry";
goto finish;
}
cumulative += goldenBerryChance / 100f;
if (spawnProbability <= cumulative)
{
if (spawnProbability <= cumulative) {
spriteRenderer.sprite = Resources.Load<Sprite>("Berries/GoldenBerry");
newBerry.tag = "GoldenBerry";
goto finish;
}
cumulative += nothingBerryChance / 100f;
if (spawnProbability <= cumulative)
{
if (spawnProbability <= cumulative) {
spriteRenderer.sprite = Resources.Load<Sprite>("Berries/BerryNoColor");
newBerry.tag = "NothingBerry";
goto finish;
@@ -419,14 +346,11 @@ public class CustomGamePlayer : MonoBehaviour
}
}
void Update()
{
foreach (AudioSource audio in FindObjectsByType<AudioSource>(FindObjectsSortMode.None))
{
void Update() {
foreach (AudioSource audio in FindObjectsByType<AudioSource>(FindObjectsSortMode.None)) {
audio.pitch = speedyLeft > 0f ? 1.3f : 1f;
}
if (screenWidth != Camera.main.orthographicSize * 2f * Camera.main.aspect)
{
if (screenWidth != Camera.main.orthographicSize * 2f * Camera.main.aspect) {
screenWidth = Camera.main.orthographicSize * 2f * Camera.main.aspect;
ClampPosition(bird);
GameObject[] allberries = GameObject.FindGameObjectsWithTag("NormalBerry")
@@ -439,8 +363,7 @@ public class CustomGamePlayer : MonoBehaviour
.Concat(GameObject.FindGameObjectsWithTag("GoldenBerry"))
.Concat(GameObject.FindGameObjectsWithTag("NothingBerry"))
.ToArray();
foreach (GameObject berry in allberries)
{
foreach (GameObject berry in allberries) {
ClampPosition(berry, false);
}
}
@@ -454,117 +377,76 @@ public class CustomGamePlayer : MonoBehaviour
GameObject[] goldenBerries = GameObject.FindGameObjectsWithTag("GoldenBerry");
GameObject[] nothingBerries = GameObject.FindGameObjectsWithTag("NothingBerry");
if (!pausePanel.activeSelf)
{
if (Time.time - lastMoveTime > 20)
{
if (!pausePanel.activeSelf) {
if (Time.time - lastMoveTime > 20) {
lastMoveTime = float.MaxValue;
EnablePause();
}
CheckIfGrounded();
foreach (GameObject normalBerry in normalBerries)
{
if (normalBerry.transform.position.y < 0f - Camera.main.orthographicSize - 1f)
{
foreach (GameObject normalBerry in normalBerries) {
if (normalBerry.transform.position.y < 0f - Camera.main.orthographicSize - 1f) {
Destroy(normalBerry);
}
else if (UnityEngine.Vector3.Distance(bird.transform.position, normalBerry.transform.position) < 1.5f)
{
} else if (UnityEngine.Vector3.Distance(bird.transform.position, normalBerry.transform.position) < 1.5f) {
DoNormalBerry(normalBerry);
}
if (speedyLeft > 0)
{
if (speedyLeft > 0) {
normalBerry.GetComponent<Rigidbody2D>().linearVelocity = new UnityEngine.Vector2(0f, -7.5f);
}
else
{
} else {
normalBerry.GetComponent<Rigidbody2D>().linearVelocity = new UnityEngine.Vector2(0f, -4f);
}
}
foreach (GameObject poisonBerry in poisonBerries)
{
if (poisonBerry.transform.position.y < 0f - Camera.main.orthographicSize - 1f)
{
foreach (GameObject poisonBerry in poisonBerries) {
if (poisonBerry.transform.position.y < 0f - Camera.main.orthographicSize - 1f) {
Destroy(poisonBerry);
}
else if (UnityEngine.Vector3.Distance(bird.transform.position, poisonBerry.transform.position) < 1.5f)
{
} else if (UnityEngine.Vector3.Distance(bird.transform.position, poisonBerry.transform.position) < 1.5f) {
DoPoisonBerry();
}
if (speedyLeft > 0)
{
if (speedyLeft > 0) {
poisonBerry.GetComponent<Rigidbody2D>().linearVelocity = new UnityEngine.Vector2(0f, -7.5f);
}
else
{
} else {
poisonBerry.GetComponent<Rigidbody2D>().linearVelocity = new UnityEngine.Vector2(0f, -4f);
}
}
foreach (GameObject slowBerry in slowBerries)
{
if (slowBerry.transform.position.y < 0f - Camera.main.orthographicSize - 1f)
{
foreach (GameObject slowBerry in slowBerries) {
if (slowBerry.transform.position.y < 0f - Camera.main.orthographicSize - 1f) {
Destroy(slowBerry);
}
else if (UnityEngine.Vector3.Distance(bird.transform.position, slowBerry.transform.position) < 1.5f)
{
} else if (UnityEngine.Vector3.Distance(bird.transform.position, slowBerry.transform.position) < 1.5f) {
DoSlowBerry(slowBerry);
}
if (speedyLeft > 0)
{
if (speedyLeft > 0) {
slowBerry.GetComponent<Rigidbody2D>().linearVelocity = new UnityEngine.Vector2(0f, -7.5f);
}
else
{
} else {
slowBerry.GetComponent<Rigidbody2D>().linearVelocity = new UnityEngine.Vector2(0f, -4f);
}
}
foreach (GameObject ultraBerry in ultraBerries)
{
if (ultraBerry.transform.position.y < 0f - Camera.main.orthographicSize - 1f)
{
foreach (GameObject ultraBerry in ultraBerries) {
if (ultraBerry.transform.position.y < 0f - Camera.main.orthographicSize - 1f) {
Destroy(ultraBerry);
}
else if (UnityEngine.Vector3.Distance(bird.transform.position, ultraBerry.transform.position) < 1.5f)
{
} else if (UnityEngine.Vector3.Distance(bird.transform.position, ultraBerry.transform.position) < 1.5f) {
DoUltraBerry(ultraBerry);
}
if (speedyLeft > 0)
{
if (speedyLeft > 0) {
ultraBerry.GetComponent<Rigidbody2D>().linearVelocity = new UnityEngine.Vector2(0f, -7.5f);
}
else
{
} else {
ultraBerry.GetComponent<Rigidbody2D>().linearVelocity = new UnityEngine.Vector2(0f, -4f);
}
}
foreach (GameObject speedyBerry in speedyBerries)
{
if (speedyBerry.transform.position.y < 0f - Camera.main.orthographicSize - 1f)
{
foreach (GameObject speedyBerry in speedyBerries) {
if (speedyBerry.transform.position.y < 0f - Camera.main.orthographicSize - 1f) {
Destroy(speedyBerry);
}
else if (UnityEngine.Vector3.Distance(bird.transform.position, speedyBerry.transform.position) < 1.5f)
{
} else if (UnityEngine.Vector3.Distance(bird.transform.position, speedyBerry.transform.position) < 1.5f) {
DoSpeedyBerry(speedyBerry);
}
if (speedyLeft > 0)
{
if (speedyLeft > 0) {
speedyBerry.GetComponent<Rigidbody2D>().linearVelocity = new UnityEngine.Vector2(0f, -7.5f);
}
else
{
} else {
speedyBerry.GetComponent<Rigidbody2D>().linearVelocity = new UnityEngine.Vector2(0f, -4f);
}
}
foreach (GameObject randomBerry in randomBerries)
{
if (randomBerry.transform.position.y < 0f - Camera.main.orthographicSize - 1f)
{
foreach (GameObject randomBerry in randomBerries) {
if (randomBerry.transform.position.y < 0f - Camera.main.orthographicSize - 1f) {
Destroy(randomBerry);
}
else if (UnityEngine.Vector3.Distance(bird.transform.position, randomBerry.transform.position) < 1.5f)
{
} else if (UnityEngine.Vector3.Distance(bird.transform.position, randomBerry.transform.position) < 1.5f) {
System.Action[] funcs = {
() => DoNormalBerry(randomBerry),
() => DoSlowBerry(randomBerry),
@@ -574,75 +456,49 @@ public class CustomGamePlayer : MonoBehaviour
};
funcs[Random.Range(0, funcs.Length)]();
}
if (speedyLeft > 0)
{
if (speedyLeft > 0) {
randomBerry.GetComponent<Rigidbody2D>().linearVelocity = new UnityEngine.Vector2(0f, -7.5f);
}
else
{
} else {
randomBerry.GetComponent<Rigidbody2D>().linearVelocity = new UnityEngine.Vector2(0f, -4f);
}
}
foreach (GameObject antiBerry in antiBerries)
{
if (antiBerry.transform.position.y < 0f - Camera.main.orthographicSize - 1f)
{
foreach (GameObject antiBerry in antiBerries) {
if (antiBerry.transform.position.y < 0f - Camera.main.orthographicSize - 1f) {
Destroy(antiBerry);
}
else if (UnityEngine.Vector3.Distance(bird.transform.position, antiBerry.transform.position) < 1.5f)
{
} else if (UnityEngine.Vector3.Distance(bird.transform.position, antiBerry.transform.position) < 1.5f) {
DoAntiBerry(antiBerry);
}
if (speedyLeft > 0)
{
if (speedyLeft > 0) {
antiBerry.GetComponent<Rigidbody2D>().linearVelocity = new UnityEngine.Vector2(0f, -7.5f);
}
else
{
} else {
antiBerry.GetComponent<Rigidbody2D>().linearVelocity = new UnityEngine.Vector2(0f, -4f);
}
}
foreach (GameObject goldenBerry in goldenBerries)
{
if (goldenBerry.transform.position.y < 0f - Camera.main.orthographicSize - 1f)
{
foreach (GameObject goldenBerry in goldenBerries) {
if (goldenBerry.transform.position.y < 0f - Camera.main.orthographicSize - 1f) {
Destroy(goldenBerry);
}
else if (UnityEngine.Vector3.Distance(bird.transform.position, goldenBerry.transform.position) < 1.5f)
{
} else if (UnityEngine.Vector3.Distance(bird.transform.position, goldenBerry.transform.position) < 1.5f) {
DoGoldenBerry(goldenBerry);
}
if (speedyLeft > 0)
{
if (speedyLeft > 0) {
goldenBerry.GetComponent<Rigidbody2D>().linearVelocity = new UnityEngine.Vector2(0f, -7.5f);
}
else
{
} else {
goldenBerry.GetComponent<Rigidbody2D>().linearVelocity = new UnityEngine.Vector2(0f, -4f);
}
}
foreach (GameObject nothingBerry in nothingBerries)
{
if (nothingBerry.transform.position.y < 0f - Camera.main.orthographicSize - 1f)
{
foreach (GameObject nothingBerry in nothingBerries) {
if (nothingBerry.transform.position.y < 0f - Camera.main.orthographicSize - 1f) {
Destroy(nothingBerry);
}
else if (UnityEngine.Vector3.Distance(bird.transform.position, nothingBerry.transform.position) < 1.5f)
{
} else if (UnityEngine.Vector3.Distance(bird.transform.position, nothingBerry.transform.position) < 1.5f) {
DoNothingBerry(nothingBerry);
}
if (speedyLeft > 0)
{
if (speedyLeft > 0) {
nothingBerry.GetComponent<Rigidbody2D>().linearVelocity = new UnityEngine.Vector2(0f, -7.5f);
}
else
{
} else {
nothingBerry.GetComponent<Rigidbody2D>().linearVelocity = new UnityEngine.Vector2(0f, -4f);
}
}
}
else
{
} else {
rb.gravityScale = 0f;
rb.linearVelocity = UnityEngine.Vector2.zero;
GameObject[] allberries = normalBerries
@@ -655,16 +511,14 @@ public class CustomGamePlayer : MonoBehaviour
.Concat(goldenBerries)
.Concat(nothingBerries)
.ToArray();
foreach (GameObject berry in allberries)
{
foreach (GameObject berry in allberries) {
berry.GetComponent<Rigidbody2D>().linearVelocity = UnityEngine.Vector2.zero;
}
}
if ((Application.platform == RuntimePlatform.Android && Keyboard.current.escapeKey.wasPressedThisFrame) || !Application.isMobilePlatform && (Keyboard.current.escapeKey.wasPressedThisFrame || (Gamepad.current != null && (Gamepad.current.startButton.wasPressedThisFrame || Gamepad.current.buttonEast.wasPressedThisFrame)))) TogglePause();
}
void Respawn()
{
void Respawn() {
bird.transform.position = new UnityEngine.Vector3(0f, -4.3f, 0f);
bird.transform.localScale = new UnityEngine.Vector3(1.35f, 1.35f, 1.35f);
rb.gravityScale = 0f;
@@ -686,14 +540,12 @@ public class CustomGamePlayer : MonoBehaviour
.Concat(GameObject.FindGameObjectsWithTag("GoldenBerry"))
.Concat(GameObject.FindGameObjectsWithTag("NothingBerry"))
.ToArray();
foreach (GameObject berry in allberries)
{
foreach (GameObject berry in allberries) {
Destroy(berry);
}
}
void UpdateStats(BigInteger scoreAddAmount)
{
void UpdateStats(BigInteger scoreAddAmount) {
score += scoreAddAmount;
scoreText.text = $"Score: {Tools.FormatWithCommas(score)}";
if (Application.isMobilePlatform) restartButton.interactable = score != 0;
@@ -701,38 +553,32 @@ public class CustomGamePlayer : MonoBehaviour
DiscordRPCHandler.Instance.UpdateRPC("Playing in custom mode", "Score: " + Tools.FormatWithCommas(score));
}
void CheckIfGrounded()
{
void CheckIfGrounded() {
isGrounded = bird.transform.position.y <= -4.1299996f;
rb.gravityScale = isGrounded ? 0f : 1.5f;
if (bird.transform.position.y < -4.1359f)
{
if (bird.transform.position.y < -4.1359f) {
bird.transform.position = new UnityEngine.Vector2(bird.transform.position.x, -4.1359f);
rb.linearVelocity = new UnityEngine.Vector2(rb.linearVelocity.x, 0f);
}
if (Application.isMobilePlatform) jumpButton.transform.GetChild(0).GetComponent<TMP_Text>().color = isGrounded ? Color.white : Color.red;
}
internal void TogglePause()
{
internal void TogglePause() {
if (pausePanel.activeSelf) DisablePause();
else EnablePause();
}
internal void EnablePause()
{
internal void EnablePause() {
Cursor.visible = true;
Cursor.lockState = CursorLockMode.None;
backgroundMusic.GetComponent<GameMusicHandler>().PauseMusic();
pausePanel.SetActive(true);
}
internal void DisablePause()
{
if (CustomGamePlayerPauseMenu.Instance.editingUI == true)
{
internal void DisablePause() {
if (CustomGamePlayerPauseMenu.Instance.editingUI == true) {
CustomGamePlayerPauseMenu.Instance.ToggleEditingUI();
return;
}
@@ -743,33 +589,28 @@ public class CustomGamePlayer : MonoBehaviour
pausePanel.SetActive(false);
}
void OnApplicationPause(bool pause)
{
void OnApplicationPause(bool pause) {
if (pause) EnablePause();
}
void OnApplicationQuit()
{
void OnApplicationQuit() {
Cursor.visible = true;
Cursor.lockState = CursorLockMode.None;
}
void DoNormalBerry(GameObject berry)
{
void DoNormalBerry(GameObject berry) {
AudioSource.PlayClipAtPoint(Resources.Load<AudioClip>("Sounds/Eat"), Camera.main.transform.position, 1.2f * BazookaManager.Instance.GetSettingSFXVolume());
Destroy(berry);
UpdateStats(1);
}
void DoPoisonBerry()
{
void DoPoisonBerry() {
AudioSource.PlayClipAtPoint(Resources.Load<AudioClip>("Sounds/Death"), Camera.main.transform.position, 1.2f * BazookaManager.Instance.GetSettingSFXVolume());
Respawn();
UpdateStats(0);
}
void DoSlowBerry(GameObject berry)
{
void DoSlowBerry(GameObject berry) {
AudioSource.PlayClipAtPoint(Resources.Load<AudioClip>("Sounds/Downgrade"), Camera.main.transform.position, 0.35f * BazookaManager.Instance.GetSettingSFXVolume());
Destroy(berry);
boostLeft = 0f;
@@ -777,33 +618,27 @@ public class CustomGamePlayer : MonoBehaviour
speedyLeft = 0f;
antiLeft = 0f;
goldenLeft = 0f;
if (score > 0)
{
if (score > 0) {
UpdateStats(-1);
}
}
void DoUltraBerry(GameObject berry)
{
void DoUltraBerry(GameObject berry) {
AudioSource.PlayClipAtPoint(Resources.Load<AudioClip>("Sounds/Powerup"), Camera.main.transform.position, 0.35f * BazookaManager.Instance.GetSettingSFXVolume());
Destroy(berry);
speedyLeft = 0f;
antiLeft = 0f;
goldenLeft = 0f;
if (slownessLeft > 0f)
{
if (slownessLeft > 0f) {
slownessLeft = 0f;
UpdateStats(1);
}
else
{
} else {
boostLeft += 10f;
UpdateStats(5);
}
}
void DoSpeedyBerry(GameObject berry)
{
void DoSpeedyBerry(GameObject berry) {
AudioSource.PlayClipAtPoint(Resources.Load<AudioClip>("Sounds/SpeedyPowerup"), Camera.main.transform.position, 0.35f * BazookaManager.Instance.GetSettingSFXVolume());
Destroy(berry);
boostLeft = 0f;
@@ -814,8 +649,7 @@ public class CustomGamePlayer : MonoBehaviour
UpdateStats(10);
}
void DoAntiBerry(GameObject berry)
{
void DoAntiBerry(GameObject berry) {
AudioSource.PlayClipAtPoint(Resources.Load<AudioClip>("Sounds/Downgrade"), Camera.main.transform.position, 0.35f * BazookaManager.Instance.GetSettingSFXVolume());
Destroy(berry);
boostLeft = 0f;
@@ -826,8 +660,7 @@ public class CustomGamePlayer : MonoBehaviour
UpdateStats(0);
}
void DoGoldenBerry(GameObject berry)
{
void DoGoldenBerry(GameObject berry) {
AudioSource.PlayClipAtPoint(Resources.Load<AudioClip>("Sounds/Powerup"), Camera.main.transform.position, 0.35f * BazookaManager.Instance.GetSettingSFXVolume());
Destroy(berry);
boostLeft = 0f;
@@ -838,8 +671,7 @@ public class CustomGamePlayer : MonoBehaviour
UpdateStats(4);
}
void DoNothingBerry(GameObject berry)
{
void DoNothingBerry(GameObject berry) {
AudioSource.PlayClipAtPoint(Resources.Load<AudioClip>("Sounds/Eat"), Camera.main.transform.position, 1.2f * BazookaManager.Instance.GetSettingSFXVolume());
Destroy(berry);
}
+14 -29
View File
@@ -2,8 +2,7 @@ using TMPro;
using UnityEngine;
using UnityEngine.UI;
public class CustomGamePlayerPauseMenu : MonoBehaviour
{
public class CustomGamePlayerPauseMenu : MonoBehaviour {
public static CustomGamePlayerPauseMenu Instance;
[SerializeField] private Button backButton;
[SerializeField] private Button continueButton;
@@ -28,31 +27,25 @@ public class CustomGamePlayerPauseMenu : MonoBehaviour
[SerializeField] private TMP_Text musicSliderText;
[SerializeField] private TMP_Text sfxSliderText;
void Awake()
{
void Awake() {
Instance = this;
continueButton.onClick.AddListener(CustomGamePlayer.instance.DisablePause);
musicSlider.onValueChanged.AddListener(value =>
{
musicSlider.onValueChanged.AddListener(value => {
BazookaManager.Instance.SetSettingMusicVolume(value);
songLoop.volume = value;
});
sfxSlider.onValueChanged.AddListener(value =>
{
sfxSlider.onValueChanged.AddListener(value => {
BazookaManager.Instance.SetSettingSFXVolume(value);
});
editUiButton.onClick.AddListener(() =>
{
editUiButton.onClick.AddListener(() => {
ToggleEditingUI();
});
resetUiButton.onClick.AddListener(() =>
{
resetUiButton.onClick.AddListener(() => {
((RectTransform)scoreText.transform).anchoredPosition = new Vector2(0f, -70f);
((RectTransform)boostText.transform).anchoredPosition = new Vector2(0f, -140f);
PlayerPrefs.DeleteKey("DraggedUIScoreText");
PlayerPrefs.DeleteKey("DraggedUIBoostTextCustom");
if (Application.isMobilePlatform)
{
if (Application.isMobilePlatform) {
((RectTransform)pauseButton.transform).anchoredPosition = new Vector2(128f, -128f);
((RectTransform)restartButton.transform).anchoredPosition = new Vector2(-128f, -128f);
((RectTransform)jumpButton.transform).anchoredPosition = new Vector2(-128f, 288f);
@@ -68,41 +61,34 @@ public class CustomGamePlayerPauseMenu : MonoBehaviour
musicSlider.value = BazookaManager.Instance.GetSettingMusicVolume();
sfxSlider.value = BazookaManager.Instance.GetSettingSFXVolume();
if (!Application.isMobilePlatform)
{
if (!Application.isMobilePlatform) {
settingFullscreenToggle.isOn = BazookaManager.Instance.GetSettingFullScreen() == true;
settingVSyncToggle.isOn = BazookaManager.Instance.GetSettingVsync() == true;
settingRandomMusicToggle.isOn = BazookaManager.Instance.GetSettingRandomMusic() == true;
settingFullscreenToggle.onValueChanged.AddListener(value =>
{
settingFullscreenToggle.onValueChanged.AddListener(value => {
BazookaManager.Instance.SetSettingFullScreen(value);
var width = Display.main.systemWidth;
var height = Display.main.systemHeight;
Screen.SetResolution(width, height, value);
});
settingVSyncToggle.onValueChanged.AddListener(value =>
{
settingVSyncToggle.onValueChanged.AddListener(value => {
BazookaManager.Instance.SetSettingVsync(value);
QualitySettings.vSyncCount = value ? 1 : -1;
});
}
else
{
} else {
settingFullscreenToggle.interactable = false;
settingVSyncToggle.interactable = false;
settingRandomMusicToggle.isOn = BazookaManager.Instance.GetSettingRandomMusic() == true;
}
settingRandomMusicToggle.onValueChanged.AddListener(value => BazookaManager.Instance.SetSettingRandomMusic(value));
musicSlider.onValueChanged.AddListener(value =>
{
musicSlider.onValueChanged.AddListener(value => {
BazookaManager.Instance.SetSettingMusicVolume(value);
CustomGamePlayer.instance.backgroundMusic.volume = value;
});
sfxSlider.onValueChanged.AddListener(value => BazookaManager.Instance.SetSettingSFXVolume(value));
}
public void ToggleEditingUI()
{
public void ToggleEditingUI() {
editingUI = !editingUI;
musicSlider.gameObject.SetActive(!musicSlider.gameObject.activeSelf);
sfxSlider.gameObject.SetActive(!sfxSlider.gameObject.activeSelf);
@@ -118,8 +104,7 @@ public class CustomGamePlayerPauseMenu : MonoBehaviour
resetUiButton.gameObject.SetActive(!resetUiButton.gameObject.activeSelf);
scoreText.GetComponent<DraggableUI>().canDrag = !scoreText.GetComponent<DraggableUI>().canDrag;
boostText.GetComponent<DraggableUI>().canDrag = !boostText.GetComponent<DraggableUI>().canDrag;
if (Application.isMobilePlatform)
{
if (Application.isMobilePlatform) {
var pauseDraggableUI = pauseButton.GetComponent<DraggableUI>();
var restartDraggableUI = restartButton.GetComponent<DraggableUI>();
var jumpDraggableUI = jumpButton.GetComponent<DraggableUI>();
+2 -4
View File
@@ -1,7 +1,6 @@
using UnityEngine;
public class CustomGameTempData : MonoBehaviour
{
public class CustomGameTempData : MonoBehaviour {
public float normalBerryChance;
public float poisonBerryChance;
public float slowBerryChance;
@@ -12,8 +11,7 @@ public class CustomGameTempData : MonoBehaviour
public float goldenBerryChance;
public float nothingBerryChance;
void Awake()
{
void Awake() {
DontDestroyOnLoad(gameObject);
}
}
+7 -14
View File
@@ -5,41 +5,34 @@ using UnityEngine;
using UnityEngine.Networking;
using UnityEngine.UI;
public class CustomIconLoader : MonoBehaviour
{
public static async void Init(WaitingForCustomIcon[] objects)
{
public class CustomIconLoader : MonoBehaviour {
public static async void Init(WaitingForCustomIcon[] objects) {
var iconsToDownload = new HashSet<string>();
foreach (var obj in objects)
if (!BazookaManager.Instance.iconCache.Any(icon => icon.ID == obj.ID))
iconsToDownload.Add(obj.ID);
if (iconsToDownload.Count != 0)
{
if (iconsToDownload.Count != 0) {
var ids = string.Join(",", iconsToDownload.Select(id => $"\"{id}\""));
using UnityWebRequest request = UnityWebRequest.Get(Endpoints.ICON_MARKETPLACE_ICON_ENDPOINT + $"?ids=[{ids}]");
request.SetRequestHeader("Requester", "BerryDashClient");
request.SetRequestHeader("ClientVersion", Application.version);
request.SetRequestHeader("ClientPlatform", Application.platform.ToString());
await request.SendWebRequest();
if (request.downloadHandler.text == null)
{
if (request.downloadHandler.text == null) {
return;
}
var jsonResponse = JObject.Parse(request.downloadHandler.text);
if ((bool)jsonResponse["success"])
{
if ((bool)jsonResponse["success"]) {
var icons = jsonResponse["data"].ToObject<MarketplaceIconWithData[]>();
foreach (var icon in icons) BazookaManager.Instance.iconCache.Add(new MarketplaceIcon { ID = icon.ID, Data = icon.Data });
}
Debug.Log($"Downloaded {iconsToDownload.Count} custom icons");
}
foreach (var obj in objects)
{
foreach (var obj in objects) {
var cachedIcon = BazookaManager.Instance.iconCache.FirstOrDefault(icon => icon.ID == obj.ID);
if (cachedIcon != null)
{
if (cachedIcon != null) {
if (obj.TryGetComponent<Image>(out var image))
image.sprite = Tools.GetSpriteFromBase64(cachedIcon.Data);
else if (obj.TryGetComponent<SpriteRenderer>(out var spriteRenderer))
+12 -25
View File
@@ -1,8 +1,7 @@
using DiscordRPC;
using UnityEngine;
public class DiscordRPCHandler : MonoBehaviour
{
public class DiscordRPCHandler : MonoBehaviour {
public static DiscordRPCHandler Instance;
public DiscordRpcClient client;
private readonly Timestamps timestamp = Timestamps.Now;
@@ -11,10 +10,8 @@ public class DiscordRPCHandler : MonoBehaviour
private string savedDetails;
private string savedState;
void Awake()
{
if (Application.isMobilePlatform || Instance != null)
{
void Awake() {
if (Application.isMobilePlatform || Instance != null) {
Destroy(gameObject);
return;
}
@@ -26,44 +23,34 @@ public class DiscordRPCHandler : MonoBehaviour
client.Initialize();
}
void OnDestroy()
{
void OnDestroy() {
client?.Dispose();
}
void OnApplicationQuit()
{
void OnApplicationQuit() {
client?.Dispose();
}
void OnApplicationPause(bool pause)
{
void OnApplicationPause(bool pause) {
isIdle = pause;
if (pause)
{
if (pause) {
UpdateRPC("Idle", null, true);
}
else
{
} else {
UpdateRPC(savedDetails, savedState, true);
}
}
public void UpdateRPC(string details, string state, bool force = false)
{
if (!force && isIdle)
{
public void UpdateRPC(string details, string state, bool force = false) {
if (!force && isIdle) {
savedDetails = details;
savedState = state;
return;
}
client.SetPresence(new RichPresence
{
client.SetPresence(new RichPresence {
Details = details,
State = state,
Assets = new Assets
{
Assets = new Assets {
LargeImageKey = "https://games-r2.lncvrt.xyz/icons/berry-dash.png",
LargeImageText = "Berry Dash",
SmallImageKey = "https://cdn.lncvrt.xyz/pfp.png",
+2 -4
View File
@@ -1,12 +1,10 @@
using UnityEngine;
public class DiscordRPCUpdater : MonoBehaviour
{
public class DiscordRPCUpdater : MonoBehaviour {
public string details;
public string state;
void Awake()
{
void Awake() {
if (DiscordRPCHandler.Instance != null) DiscordRPCHandler.Instance.UpdateRPC(details, state);
}
}
+11 -22
View File
@@ -3,8 +3,7 @@ using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.UI;
public class DraggableUI : MonoBehaviour, IDragHandler, IBeginDragHandler
{
public class DraggableUI : MonoBehaviour, IDragHandler, IBeginDragHandler {
public static DraggableUI Instance;
private Vector2 offset;
[SerializeField] private string uiName;
@@ -12,8 +11,7 @@ public class DraggableUI : MonoBehaviour, IDragHandler, IBeginDragHandler
private readonly List<GameObject> outlineSides = new();
void CreateOutline()
{
void CreateOutline() {
var color = BazookaManager.Instance.GetColorSettingButton();
Color borderColor = new(((float)color[0]) / 255f, ((float)color[1]) / 255f, ((float)color[2]) / 255f);
float thickness = 2f;
@@ -24,8 +22,7 @@ public class DraggableUI : MonoBehaviour, IDragHandler, IBeginDragHandler
CreateSide("Right", new Vector2(1, 0), new Vector2(1, 1), new Vector2(thickness, 0), borderColor);
}
void CreateSide(string name, Vector2 anchorMin, Vector2 anchorMax, Vector2 size, Color color)
{
void CreateSide(string name, Vector2 anchorMin, Vector2 anchorMax, Vector2 size, Color color) {
var go = new GameObject(name, typeof(Image));
go.transform.SetParent(transform, false);
var rt = go.GetComponent<RectTransform>();
@@ -41,30 +38,25 @@ public class DraggableUI : MonoBehaviour, IDragHandler, IBeginDragHandler
outlineSides.Add(go);
}
void Awake()
{
void Awake() {
Instance = this;
}
void Start()
{
void Start() {
CreateOutline();
}
void OnEnable()
{
void OnEnable() {
string key = "DraggedUI" + uiName;
if (PlayerPrefs.HasKey(key) && TryParseVector3(PlayerPrefs.GetString(key), out Vector3 savedPos)) transform.localPosition = savedPos;
}
void Update()
{
void Update() {
foreach (var side in outlineSides)
side.SetActive(canDrag);
}
public void OnBeginDrag(PointerEventData eventData)
{
public void OnBeginDrag(PointerEventData eventData) {
if (!canDrag) return;
RectTransformUtility.ScreenPointToLocalPointInRectangle(
(RectTransform)transform.parent,
@@ -76,8 +68,7 @@ public class DraggableUI : MonoBehaviour, IDragHandler, IBeginDragHandler
PlayerPrefs.SetString("DraggedUI" + uiName, transform.localPosition.ToString());
}
public void OnDrag(PointerEventData eventData)
{
public void OnDrag(PointerEventData eventData) {
if (!canDrag) return;
if (RectTransformUtility.ScreenPointToLocalPointInRectangle(
(RectTransform)transform.parent,
@@ -88,15 +79,13 @@ public class DraggableUI : MonoBehaviour, IDragHandler, IBeginDragHandler
PlayerPrefs.SetString("DraggedUI" + uiName, transform.localPosition.ToString());
}
private bool TryParseVector3(string s, out Vector3 result)
{
private bool TryParseVector3(string s, out Vector3 result) {
s = s.Trim('(', ')');
string[] parts = s.Split(',');
if (parts.Length == 3 &&
float.TryParse(parts[0], out float x) &&
float.TryParse(parts[1], out float y) &&
float.TryParse(parts[2], out float z))
{
float.TryParse(parts[2], out float z)) {
result = new Vector3(x, y, z);
return true;
}
+11 -23
View File
@@ -1,37 +1,30 @@
using UnityEngine;
[RequireComponent(typeof(AudioSource))]
public class GameMusicHandler : MonoBehaviour
{
public class GameMusicHandler : MonoBehaviour {
[SerializeField] private AudioClip[] audioClips;
private AudioSource audioSource;
private int lastIndex = -1;
private int currentIndex = 0;
private bool isPaused = false;
void Start()
{
void Start() {
audioSource = GetComponent<AudioSource>();
PlayNextClip();
}
void Update()
{
void Update() {
if (!audioSource.isPlaying && !isPaused) PlayNextClip();
}
void PlayNextClip()
{
void PlayNextClip() {
if (audioClips.Length == 0) return;
int index;
if (BazookaManager.Instance.GetSettingRandomMusic())
{
if (BazookaManager.Instance.GetSettingRandomMusic()) {
do index = Random.Range(0, audioClips.Length);
while (audioClips.Length > 1 && index == lastIndex);
}
else
{
} else {
index = currentIndex;
currentIndex = (currentIndex + 1) % audioClips.Length;
}
@@ -41,26 +34,21 @@ public class GameMusicHandler : MonoBehaviour
audioSource.Play();
}
public void PauseMusic()
{
if (audioSource.isPlaying)
{
public void PauseMusic() {
if (audioSource.isPlaying) {
audioSource.Pause();
isPaused = true;
}
}
public void ResumeMusic()
{
if (isPaused)
{
public void ResumeMusic() {
if (isPaused) {
audioSource.Play();
isPaused = false;
}
}
public void RestartMusic()
{
public void RestartMusic() {
audioSource.Stop();
audioSource.Play();
}
+136 -313
View File
@@ -1,4 +1,4 @@
using System;
using System;
using System.Linq;
using System.Numerics;
using TMPro;
@@ -6,8 +6,7 @@ using UnityEngine;
using UnityEngine.InputSystem;
using UnityEngine.UI;
public class GamePlayer : MonoBehaviour
{
public class GamePlayer : MonoBehaviour {
public static GamePlayer instance;
private readonly float spawnRate = 1f;
private float nextSpawnTime;
@@ -52,8 +51,7 @@ public class GamePlayer : MonoBehaviour
[SerializeField] private Button rightButton;
[SerializeField] private Button leftButton;
void Start()
{
void Start() {
var backgroundColor = BazookaManager.Instance.GetColorSettingBackground();
Camera.main.backgroundColor = new Color(
int.Parse(backgroundColor[0].ToString()) / 255f,
@@ -63,8 +61,7 @@ public class GamePlayer : MonoBehaviour
var customIconData = BazookaManager.Instance.GetCustomBirdIconData();
SpriteRenderer birdRender = bird.GetComponent<SpriteRenderer>();
if (customIconData.Selected == null)
{
if (customIconData.Selected == null) {
var birdColor = BazookaManager.Instance.GetColorSettingIcon();
var overlayColor = BazookaManager.Instance.GetColorSettingOverlay();
bird.GetComponent<SpriteRenderer>().color = new Color(
@@ -80,49 +77,35 @@ public class GamePlayer : MonoBehaviour
int icon = BazookaManager.Instance.GetBirdIcon();
int iconOverlay = BazookaManager.Instance.GetBirdOverlay();
if (icon == 1)
{
if (icon == 1) {
birdRender.sprite = Tools.GetIconForUser(BazookaManager.Instance.GetAccountID() ?? 0);
}
else
{
} else {
birdRender.sprite = Resources.Load<Sprite>("Icons/Icons/bird_" + icon);
}
if (iconOverlay == 8)
{
if (iconOverlay == 8) {
overlayRender.sprite = Resources.Load<Sprite>("Icons/Overlays/overlay_" + iconOverlay);
overlayRender.transform.localPosition = new UnityEngine.Vector3(-0.37f, 0.32f, 0f);
}
else if (iconOverlay == 11)
{
} else if (iconOverlay == 11) {
overlayRender.sprite = Resources.Load<Sprite>("Icons/Overlays/overlay_" + iconOverlay);
overlayRender.transform.localScale = new UnityEngine.Vector3(1.1f, 1.1f, 1.1f); //yea i didnt feel like doing it for all lmao
overlayRender.transform.localPosition = new UnityEngine.Vector3(-0.3141809f, 0.4324968f, 0f);
}
else if (iconOverlay == 13)
{
} else if (iconOverlay == 13) {
overlayRender.sprite = Resources.Load<Sprite>("Icons/Overlays/overlay_" + iconOverlay);
overlayRender.transform.localPosition = new UnityEngine.Vector3(-0.3559977f, 0.3179995f, 0f);
}
else
{
} else {
overlayRender.sprite = Resources.Load<Sprite>("Icons/Overlays/overlay_" + iconOverlay);
}
if (birdRender.sprite == null)
{
if (birdRender.sprite == null) {
birdRender.sprite = Resources.Load<Sprite>("Icons/Icons/bird_1");
BazookaManager.Instance.SetBirdIcon(1);
}
if (overlayRender.sprite == null && iconOverlay != 0)
{
if (overlayRender.sprite == null && iconOverlay != 0) {
overlayRender.sprite = Resources.Load<Sprite>("Icons/Overlays/overlay_1");
BazookaManager.Instance.SetBirdOverlay(1);
}
}
else if (customIconData.Selected != null)
} else if (customIconData.Selected != null)
foreach (var icon in customIconData.Purchased)
if (icon == customIconData.Selected)
{
if (icon == customIconData.Selected) {
var waitingForCustomIcon = birdRender.gameObject.AddComponent<WaitingForCustomIcon>();
waitingForCustomIcon.ID = customIconData.Selected;
CustomIconLoader.Init(new[] { waitingForCustomIcon });
@@ -152,8 +135,7 @@ public class GamePlayer : MonoBehaviour
UpdateStats(0, 1);
}
void MoveBird()
{
void MoveBird() {
float screenWidth = Camera.main.orthographicSize * 2f * Camera.main.aspect;
float baseSpeed = 0.18f * (screenWidth / 20.19257f);
bool doMoveRight = false;
@@ -162,42 +144,31 @@ public class GamePlayer : MonoBehaviour
bool doRestart = false;
bool doBack = false;
float movespeed = baseSpeed;
if (boostLeft > 0f || speedyLeft > 0f)
{
if (boostLeft > 0f || speedyLeft > 0f) {
movespeed = baseSpeed * 1.39f;
}
else if (slownessLeft > 0f)
{
} else if (slownessLeft > 0f) {
movespeed = baseSpeed * 0.56f;
}
CheckIfGrounded();
bool controllerLeft = Gamepad.current != null && (Gamepad.current.leftStick.left.isPressed || Gamepad.current.dpad.left.isPressed || Gamepad.current.rightStick.left.isPressed);
bool controllerRight = Gamepad.current != null && (Gamepad.current.leftStick.right.isPressed || Gamepad.current.dpad.right.isPressed || Gamepad.current.rightStick.right.isPressed);
bool controllerJump = Gamepad.current != null && (Gamepad.current.leftStick.up.isPressed || Gamepad.current.leftStick.down.isPressed || Gamepad.current.dpad.up.isPressed || Gamepad.current.dpad.down.isPressed || Gamepad.current.rightStick.up.isPressed || Gamepad.current.rightStick.down.isPressed);
if (!Application.isMobilePlatform)
{
if (controllerLeft || Keyboard.current.leftArrowKey.isPressed || Keyboard.current.aKey.isPressed || Keyboard.current.jKey.isPressed)
{
if (!Application.isMobilePlatform) {
if (controllerLeft || Keyboard.current.leftArrowKey.isPressed || Keyboard.current.aKey.isPressed || Keyboard.current.jKey.isPressed) {
doMoveLeft = true;
}
if (controllerRight || Keyboard.current.rightArrowKey.isPressed || Keyboard.current.dKey.isPressed || Keyboard.current.lKey.isPressed)
{
if (controllerRight || Keyboard.current.rightArrowKey.isPressed || Keyboard.current.dKey.isPressed || Keyboard.current.lKey.isPressed) {
doMoveRight = true;
}
if (controllerJump || Keyboard.current.spaceKey.isPressed || Keyboard.current.upArrowKey.isPressed || Keyboard.current.wKey.isPressed || Keyboard.current.downArrowKey.isPressed || Keyboard.current.sKey.isPressed || Keyboard.current.kKey.isPressed || Keyboard.current.iKey.isPressed || Mouse.current.leftButton.isPressed || (Gamepad.current != null && Gamepad.current.buttonSouth.isPressed))
{
if (controllerJump || Keyboard.current.spaceKey.isPressed || Keyboard.current.upArrowKey.isPressed || Keyboard.current.wKey.isPressed || Keyboard.current.downArrowKey.isPressed || Keyboard.current.sKey.isPressed || Keyboard.current.kKey.isPressed || Keyboard.current.iKey.isPressed || Mouse.current.leftButton.isPressed || (Gamepad.current != null && Gamepad.current.buttonSouth.isPressed)) {
doJump = true;
}
if (Keyboard.current.rKey.isPressed)
{
if (Keyboard.current.rKey.isPressed) {
doRestart = true;
}
}
else
{
} else {
var touches = UnityEngine.InputSystem.EnhancedTouch.Touch.activeTouches;
for (int i = 0; i < touches.Count; i++)
{
for (int i = 0; i < touches.Count; i++) {
var pos = touches[i].screenPosition;
UnityEngine.Vector3 clickPosition = Camera.main.ScreenToWorldPoint(new UnityEngine.Vector3(pos.x, pos.y, 0f));
clickPosition.z = 0f;
@@ -208,56 +179,42 @@ public class GamePlayer : MonoBehaviour
if (pauseButton.GetComponent<HoldableButton>().isPressed) doBack = true;
}
}
if (doMoveLeft && !doMoveRight)
{
if (doMoveLeft && !doMoveRight) {
lastMoveTime = Time.time;
bird.transform.position += new UnityEngine.Vector3(-movespeed, 0f, 0f);
ClampPosition(bird);
bird.transform.localScale = new UnityEngine.Vector3(1.35f, 1.35f, 1.35f);
}
if (doMoveRight && !doMoveLeft)
{
if (doMoveRight && !doMoveLeft) {
lastMoveTime = Time.time;
bird.transform.position += new UnityEngine.Vector3(movespeed, 0f, 0f);
ClampPosition(bird);
bird.transform.localScale = new UnityEngine.Vector3(-1.35f, 1.35f, 1.35f);
}
if (doJump && isGrounded)
{
if (doJump && isGrounded) {
lastMoveTime = Time.time;
AudioSource.PlayClipAtPoint(Resources.Load<AudioClip>("Sounds/Jump"), Camera.main.transform.position, 0.75f * BazookaManager.Instance.GetSettingSFXVolume());
if (boostLeft > 0f || speedyLeft > 0f)
{
if (boostLeft > 0f || speedyLeft > 0f) {
rb.linearVelocity = UnityEngine.Vector2.up * 12f;
}
else if (slownessLeft > 0f)
{
} else if (slownessLeft > 0f) {
rb.linearVelocity = UnityEngine.Vector2.up * 6f;
}
else
{
} else {
rb.linearVelocity = UnityEngine.Vector2.up * 9f;
}
}
if (doBack)
{
if (doBack) {
TogglePause();
}
if (doRestart)
{
if (doRestart) {
if (score != 0) Respawn();
}
if (antiLeft > 0f || goldenLeft > 0f)
{
if (antiLeft > 0f || goldenLeft > 0f) {
string[] berryTags = { "NormalBerry", "SlowBerry", "UltraBerry", "SpeedyBerry", "CoinBerry", "RandomBerry", "AntiBerry", "GoldenBerry" };
if (antiLeft > 0f) berryTags.Append("PoisonBerry");
foreach (string tag in berryTags)
{
foreach (var berry in GameObject.FindGameObjectsWithTag(tag))
{
foreach (string tag in berryTags) {
foreach (var berry in GameObject.FindGameObjectsWithTag(tag)) {
UnityEngine.Vector3 dir = berry.transform.position - bird.transform.position;
if (dir.magnitude < (antiLeft > 0 ? 3f : 4.5f))
{
if (dir.magnitude < (antiLeft > 0 ? 3f : 4.5f)) {
berry.GetComponent<Rigidbody2D>().linearVelocity = dir.normalized * (antiLeft > 0 ? 5f : -5f);
ClampPosition(berry, false);
}
@@ -266,8 +223,7 @@ public class GamePlayer : MonoBehaviour
}
}
void ClampPosition(GameObject obj, bool modifyY = true)
{
void ClampPosition(GameObject obj, bool modifyY = true) {
var cam = Camera.main;
var pos = obj.transform.position;
var bounds = obj.GetComponent<Renderer>().bounds.extents;
@@ -283,108 +239,72 @@ public class GamePlayer : MonoBehaviour
obj.transform.position = pos;
}
void FixedUpdate()
{
void FixedUpdate() {
SpawnBerries();
if (!pausePanel.activeSelf)
{
if (!pausePanel.activeSelf) {
MoveBird();
if (boostLeft > 0f)
{
if (boostLeft > 0f) {
boostLeft -= Time.deltaTime;
boostText.text = "Boost expires in " + string.Format("{0:0.0}", boostLeft) + "s";
}
else if (slownessLeft > 0f)
{
} else if (slownessLeft > 0f) {
slownessLeft -= Time.deltaTime;
boostText.text = "Slowness expires in " + string.Format("{0:0.0}", slownessLeft) + "s";
}
else if (speedyLeft > 0f)
{
} else if (speedyLeft > 0f) {
speedyLeft -= Time.deltaTime;
boostText.text = "Speed expires in " + string.Format("{0:0.0}", speedyLeft) + "s";
}
else if (antiLeft > 0f)
{
} else if (antiLeft > 0f) {
antiLeft -= Time.deltaTime;
boostText.text = "Berry repellent expires in " + string.Format("{0:0.0}", antiLeft) + "s";
}
else if (goldenLeft > 0f)
{
} else if (goldenLeft > 0f) {
goldenLeft -= Time.deltaTime;
boostText.text = "Berry magnet expires in " + string.Format("{0:0.0}", goldenLeft) + "s";
}
else
{
} else {
boostText.text = "";
}
}
}
void SpawnBerries()
{
if (Time.time < nextSpawnTime)
{
void SpawnBerries() {
if (Time.time < nextSpawnTime) {
return;
}
if (speedyLeft > 0)
{
if (speedyLeft > 0) {
nextSpawnTime = Time.time + 1f / (spawnRate * 1.875f);
}
else
{
} else {
nextSpawnTime = Time.time + 1f / spawnRate;
}
float spawnProbability = UnityEngine.Random.value;
if (!pausePanel.activeSelf)
{
if (!pausePanel.activeSelf) {
GameObject newBerry = new("Berry");
newBerry.transform.SetParent(berryParent.transform);
SpriteRenderer spriteRenderer = newBerry.AddComponent<SpriteRenderer>();
if (spawnProbability <= 0.375f)
{
if (spawnProbability <= 0.375f) {
spriteRenderer.sprite = Resources.Load<Sprite>("Berries/Berry");
newBerry.tag = "NormalBerry";
}
else if (spawnProbability <= 0.550)
{
} else if (spawnProbability <= 0.550) {
spriteRenderer.sprite = Resources.Load<Sprite>("Berries/PoisonBerry");
newBerry.tag = "PoisonBerry";
}
else if (spawnProbability <= 0.60f)
{
} else if (spawnProbability <= 0.60f) {
spriteRenderer.sprite = Resources.Load<Sprite>("Berries/SlowBerry");
newBerry.tag = "SlowBerry";
}
else if (spawnProbability <= 0.70f)
{
} else if (spawnProbability <= 0.70f) {
spriteRenderer.sprite = Resources.Load<Sprite>("Berries/UltraBerry");
newBerry.tag = "UltraBerry";
}
else if (spawnProbability <= 0.80f)
{
} else if (spawnProbability <= 0.80f) {
spriteRenderer.sprite = Resources.Load<Sprite>("Berries/SpeedyBerry");
newBerry.tag = "SpeedyBerry";
}
else if (spawnProbability <= 0.85f)
{
} else if (spawnProbability <= 0.85f) {
spriteRenderer.sprite = Resources.Load<Sprite>("Berries/CoinBerry");
newBerry.tag = "CoinBerry";
}
else if (spawnProbability <= 0.90f)
{
} else if (spawnProbability <= 0.90f) {
spriteRenderer.sprite = Resources.Load<Sprite>("Berries/BerryNoColor");
newBerry.tag = "RandomBerry";
RainbowSpriteRender randomBerryRainbowImage = newBerry.AddComponent<RainbowSpriteRender>();
randomBerryRainbowImage.frequency = 5f;
}
else if (spawnProbability <= 0.95f)
{
} else if (spawnProbability <= 0.95f) {
spriteRenderer.sprite = Resources.Load<Sprite>("Berries/AntiBerry");
newBerry.tag = "AntiBerry";
}
else
{
} else {
spriteRenderer.sprite = Resources.Load<Sprite>("Berries/GoldenBerry");
newBerry.tag = "GoldenBerry";
}
@@ -400,14 +320,11 @@ public class GamePlayer : MonoBehaviour
}
}
void Update()
{
foreach (AudioSource audio in FindObjectsByType<AudioSource>(FindObjectsSortMode.None))
{
void Update() {
foreach (AudioSource audio in FindObjectsByType<AudioSource>(FindObjectsSortMode.None)) {
audio.pitch = speedyLeft > 0f ? 1.3f : 1f;
}
if (screenWidth != Camera.main.orthographicSize * 2f * Camera.main.aspect)
{
if (screenWidth != Camera.main.orthographicSize * 2f * Camera.main.aspect) {
screenWidth = Camera.main.orthographicSize * 2f * Camera.main.aspect;
ClampPosition(bird);
GameObject[] allberries = GameObject.FindGameObjectsWithTag("NormalBerry")
@@ -420,8 +337,7 @@ public class GamePlayer : MonoBehaviour
.Concat(GameObject.FindGameObjectsWithTag("AntiBerry"))
.Concat(GameObject.FindGameObjectsWithTag("GoldenBerry"))
.ToArray();
foreach (GameObject berry in allberries)
{
foreach (GameObject berry in allberries) {
ClampPosition(berry, false);
}
}
@@ -435,142 +351,94 @@ public class GamePlayer : MonoBehaviour
GameObject[] antiBerries = GameObject.FindGameObjectsWithTag("AntiBerry");
GameObject[] goldenBerries = GameObject.FindGameObjectsWithTag("GoldenBerry");
if (!pausePanel.activeSelf)
{
if (Time.time - lastMoveTime > 20)
{
if (!pausePanel.activeSelf) {
if (Time.time - lastMoveTime > 20) {
lastMoveTime = float.MaxValue;
EnablePause();
}
CheckIfGrounded();
foreach (GameObject normalBerry in normalBerries)
{
if (normalBerry.transform.position.y < 0f - Camera.main.orthographicSize - 1f)
{
foreach (GameObject normalBerry in normalBerries) {
if (normalBerry.transform.position.y < 0f - Camera.main.orthographicSize - 1f) {
Destroy(normalBerry);
}
else if (UnityEngine.Vector3.Distance(bird.transform.position, normalBerry.transform.position) < 1.5f)
{
} else if (UnityEngine.Vector3.Distance(bird.transform.position, normalBerry.transform.position) < 1.5f) {
totalNormalBerries++;
DoNormalBerry(normalBerry);
}
if (speedyLeft > 0)
{
if (speedyLeft > 0) {
normalBerry.GetComponent<Rigidbody2D>().linearVelocity = new UnityEngine.Vector2(0f, -7.5f);
}
else
{
} else {
normalBerry.GetComponent<Rigidbody2D>().linearVelocity = new UnityEngine.Vector2(0f, -4f);
}
}
foreach (GameObject poisonBerry in poisonBerries)
{
if (poisonBerry.transform.position.y < 0f - Camera.main.orthographicSize - 1f)
{
foreach (GameObject poisonBerry in poisonBerries) {
if (poisonBerry.transform.position.y < 0f - Camera.main.orthographicSize - 1f) {
Destroy(poisonBerry);
}
else if (UnityEngine.Vector3.Distance(bird.transform.position, poisonBerry.transform.position) < 1.5f)
{
} else if (UnityEngine.Vector3.Distance(bird.transform.position, poisonBerry.transform.position) < 1.5f) {
totalPoisonBerries++;
DoPoisonBerry();
}
if (speedyLeft > 0)
{
if (speedyLeft > 0) {
poisonBerry.GetComponent<Rigidbody2D>().linearVelocity = new UnityEngine.Vector2(0f, -7.5f);
}
else
{
} else {
poisonBerry.GetComponent<Rigidbody2D>().linearVelocity = new UnityEngine.Vector2(0f, -4f);
}
}
foreach (GameObject slowBerry in slowBerries)
{
if (slowBerry.transform.position.y < 0f - Camera.main.orthographicSize - 1f)
{
foreach (GameObject slowBerry in slowBerries) {
if (slowBerry.transform.position.y < 0f - Camera.main.orthographicSize - 1f) {
Destroy(slowBerry);
}
else if (UnityEngine.Vector3.Distance(bird.transform.position, slowBerry.transform.position) < 1.5f)
{
} else if (UnityEngine.Vector3.Distance(bird.transform.position, slowBerry.transform.position) < 1.5f) {
totalSlowBerries++;
DoSlowBerry(slowBerry);
}
if (speedyLeft > 0)
{
if (speedyLeft > 0) {
slowBerry.GetComponent<Rigidbody2D>().linearVelocity = new UnityEngine.Vector2(0f, -7.5f);
}
else
{
} else {
slowBerry.GetComponent<Rigidbody2D>().linearVelocity = new UnityEngine.Vector2(0f, -4f);
}
}
foreach (GameObject ultraBerry in ultraBerries)
{
if (ultraBerry.transform.position.y < 0f - Camera.main.orthographicSize - 1f)
{
foreach (GameObject ultraBerry in ultraBerries) {
if (ultraBerry.transform.position.y < 0f - Camera.main.orthographicSize - 1f) {
Destroy(ultraBerry);
}
else if (UnityEngine.Vector3.Distance(bird.transform.position, ultraBerry.transform.position) < 1.5f)
{
} else if (UnityEngine.Vector3.Distance(bird.transform.position, ultraBerry.transform.position) < 1.5f) {
totalUltraBerries++;
DoUltraBerry(ultraBerry);
}
if (speedyLeft > 0)
{
if (speedyLeft > 0) {
ultraBerry.GetComponent<Rigidbody2D>().linearVelocity = new UnityEngine.Vector2(0f, -7.5f);
}
else
{
} else {
ultraBerry.GetComponent<Rigidbody2D>().linearVelocity = new UnityEngine.Vector2(0f, -4f);
}
}
foreach (GameObject speedyBerry in speedyBerries)
{
if (speedyBerry.transform.position.y < 0f - Camera.main.orthographicSize - 1f)
{
foreach (GameObject speedyBerry in speedyBerries) {
if (speedyBerry.transform.position.y < 0f - Camera.main.orthographicSize - 1f) {
Destroy(speedyBerry);
}
else if (UnityEngine.Vector3.Distance(bird.transform.position, speedyBerry.transform.position) < 1.5f)
{
} else if (UnityEngine.Vector3.Distance(bird.transform.position, speedyBerry.transform.position) < 1.5f) {
totalSpeedyBerries++;
DoSpeedyBerry(speedyBerry);
}
if (speedyLeft > 0)
{
if (speedyLeft > 0) {
speedyBerry.GetComponent<Rigidbody2D>().linearVelocity = new UnityEngine.Vector2(0f, -7.5f);
}
else
{
} else {
speedyBerry.GetComponent<Rigidbody2D>().linearVelocity = new UnityEngine.Vector2(0f, -4f);
}
}
foreach (GameObject coinBerry in coinBerries)
{
if (coinBerry.transform.position.y < 0f - Camera.main.orthographicSize - 1f)
{
foreach (GameObject coinBerry in coinBerries) {
if (coinBerry.transform.position.y < 0f - Camera.main.orthographicSize - 1f) {
Destroy(coinBerry);
}
else if (UnityEngine.Vector3.Distance(bird.transform.position, coinBerry.transform.position) < 1.5f)
{
} else if (UnityEngine.Vector3.Distance(bird.transform.position, coinBerry.transform.position) < 1.5f) {
totalCoinBerries++;
DoCoinBerry(coinBerry);
}
if (speedyLeft > 0)
{
if (speedyLeft > 0) {
coinBerry.GetComponent<Rigidbody2D>().linearVelocity = new UnityEngine.Vector2(0f, -7.5f);
}
else
{
} else {
coinBerry.GetComponent<Rigidbody2D>().linearVelocity = new UnityEngine.Vector2(0f, -4f);
}
}
foreach (GameObject randomBerry in randomBerries)
{
if (randomBerry.transform.position.y < 0f - Camera.main.orthographicSize - 1f)
{
foreach (GameObject randomBerry in randomBerries) {
if (randomBerry.transform.position.y < 0f - Camera.main.orthographicSize - 1f) {
Destroy(randomBerry);
}
else if (UnityEngine.Vector3.Distance(bird.transform.position, randomBerry.transform.position) < 1.5f)
{
} else if (UnityEngine.Vector3.Distance(bird.transform.position, randomBerry.transform.position) < 1.5f) {
totalRandomBerries++;
Action[] funcs = {
() => DoNormalBerry(randomBerry),
@@ -582,58 +450,39 @@ public class GamePlayer : MonoBehaviour
};
funcs[UnityEngine.Random.Range(0, funcs.Length)]();
}
if (speedyLeft > 0)
{
if (speedyLeft > 0) {
randomBerry.GetComponent<Rigidbody2D>().linearVelocity = new UnityEngine.Vector2(0f, -7.5f);
}
else
{
} else {
randomBerry.GetComponent<Rigidbody2D>().linearVelocity = new UnityEngine.Vector2(0f, -4f);
}
}
foreach (GameObject antiBerry in antiBerries)
{
if (antiBerry.transform.position.y < 0f - Camera.main.orthographicSize - 1f)
{
foreach (GameObject antiBerry in antiBerries) {
if (antiBerry.transform.position.y < 0f - Camera.main.orthographicSize - 1f) {
Destroy(antiBerry);
}
else if (UnityEngine.Vector3.Distance(bird.transform.position, antiBerry.transform.position) < 1.5f)
{
} else if (UnityEngine.Vector3.Distance(bird.transform.position, antiBerry.transform.position) < 1.5f) {
totalAntiBerries++;
DoAntiBerry(antiBerry);
}
if (speedyLeft > 0)
{
if (speedyLeft > 0) {
antiBerry.GetComponent<Rigidbody2D>().linearVelocity = new UnityEngine.Vector2(0f, -7.5f);
}
else
{
} else {
antiBerry.GetComponent<Rigidbody2D>().linearVelocity = new UnityEngine.Vector2(0f, -4f);
}
}
foreach (GameObject goldenBerry in goldenBerries)
{
if (goldenBerry.transform.position.y < 0f - Camera.main.orthographicSize - 1f)
{
foreach (GameObject goldenBerry in goldenBerries) {
if (goldenBerry.transform.position.y < 0f - Camera.main.orthographicSize - 1f) {
Destroy(goldenBerry);
}
else if (UnityEngine.Vector3.Distance(bird.transform.position, goldenBerry.transform.position) < 1.5f)
{
} else if (UnityEngine.Vector3.Distance(bird.transform.position, goldenBerry.transform.position) < 1.5f) {
totalGoldenBerries++;
DoGoldenBerry(goldenBerry);
}
if (speedyLeft > 0)
{
if (speedyLeft > 0) {
goldenBerry.GetComponent<Rigidbody2D>().linearVelocity = new UnityEngine.Vector2(0f, -7.5f);
}
else
{
} else {
goldenBerry.GetComponent<Rigidbody2D>().linearVelocity = new UnityEngine.Vector2(0f, -4f);
}
}
}
else
{
} else {
rb.gravityScale = 0f;
rb.linearVelocity = UnityEngine.Vector2.zero;
GameObject[] allberries = normalBerries
@@ -646,16 +495,14 @@ public class GamePlayer : MonoBehaviour
.Concat(antiBerries)
.Concat(goldenBerries)
.ToArray();
foreach (GameObject berry in allberries)
{
foreach (GameObject berry in allberries) {
berry.GetComponent<Rigidbody2D>().linearVelocity = UnityEngine.Vector2.zero;
}
}
if ((Application.platform == RuntimePlatform.Android && Keyboard.current.escapeKey.wasPressedThisFrame) || !Application.isMobilePlatform && (Keyboard.current.escapeKey.wasPressedThisFrame || (Gamepad.current != null && (Gamepad.current.startButton.wasPressedThisFrame || Gamepad.current.buttonEast.wasPressedThisFrame)))) TogglePause();
}
void Respawn()
{
void Respawn() {
bird.transform.position = new UnityEngine.Vector3(0f, -4.3f, 0f);
bird.transform.localScale = new UnityEngine.Vector3(1.35f, 1.35f, 1.35f);
rb.gravityScale = 0f;
@@ -677,22 +524,19 @@ public class GamePlayer : MonoBehaviour
.Concat(GameObject.FindGameObjectsWithTag("AntiBerry"))
.Concat(GameObject.FindGameObjectsWithTag("GoldenBerry"))
.ToArray();
foreach (GameObject berry in allberries)
{
foreach (GameObject berry in allberries) {
Destroy(berry);
}
}
void UpdateStats(BigInteger scoreAddAmount, BigInteger attemptAddAmount)
{
void UpdateStats(BigInteger scoreAddAmount, BigInteger attemptAddAmount) {
var levelBefore = Tools.GetLevelInfo().level;
var prefix = "";
var suffix = "";
score += scoreAddAmount;
totalAttempts += attemptAddAmount;
attempts += attemptAddAmount;
if (score >= highscore)
{
if (score >= highscore) {
highscore = score;
prefix = "<color=#7FFFD4>";
suffix = "</color>";
@@ -722,14 +566,12 @@ public class GamePlayer : MonoBehaviour
if (level != levelBefore) AudioSource.PlayClipAtPoint(Resources.Load<AudioClip>("Sounds/Levelup"), Camera.main.transform.position, 1f * BazookaManager.Instance.GetSettingSFXVolume());
}
void CheckIfGrounded()
{
void CheckIfGrounded() {
isGrounded = bird.transform.position.y <= -4.1299996f;
rb.gravityScale = isGrounded ? 0f : 1.5f;
if (bird.transform.position.y < -4.1359f)
{
if (bird.transform.position.y < -4.1359f) {
bird.transform.position = new UnityEngine.Vector2(bird.transform.position.x, -4.1359f);
rb.linearVelocity = new UnityEngine.Vector2(rb.linearVelocity.x, 0f);
}
@@ -737,29 +579,24 @@ public class GamePlayer : MonoBehaviour
if (Application.isMobilePlatform) jumpButton.transform.GetChild(0).GetComponent<TMP_Text>().color = isGrounded ? new Color(int.Parse(btnColor[0].ToString()) / 255f, int.Parse(btnColor[1].ToString()) / 255f, int.Parse(btnColor[2].ToString()) / 255f) : Color.red;
}
internal void TogglePause()
{
internal void TogglePause() {
if (pausePanel.activeSelf) DisablePause();
else EnablePause();
}
internal void EnablePause()
{
internal void EnablePause() {
Cursor.visible = true;
Cursor.lockState = CursorLockMode.None;
backgroundMusic.GetComponent<GameMusicHandler>().PauseMusic();
pausePanel.SetActive(true);
}
internal void DisablePause()
{
if (GamePlayerPauseMenu.Instance.statsMenu.activeSelf)
{
internal void DisablePause() {
if (GamePlayerPauseMenu.Instance.statsMenu.activeSelf) {
GamePlayerPauseMenu.Instance.statsMenuExitButton.onClick.Invoke();
return;
}
if (GamePlayerPauseMenu.Instance.editingUI == true)
{
if (GamePlayerPauseMenu.Instance.editingUI == true) {
GamePlayerPauseMenu.Instance.ToggleEditingUI();
return;
}
@@ -770,33 +607,28 @@ public class GamePlayer : MonoBehaviour
pausePanel.SetActive(false);
}
void OnApplicationPause(bool pause)
{
void OnApplicationPause(bool pause) {
if (pause) EnablePause();
}
void OnApplicationQuit()
{
void OnApplicationQuit() {
Cursor.visible = true;
Cursor.lockState = CursorLockMode.None;
}
void DoNormalBerry(GameObject berry)
{
void DoNormalBerry(GameObject berry) {
AudioSource.PlayClipAtPoint(Resources.Load<AudioClip>("Sounds/Eat"), Camera.main.transform.position, 1.2f * BazookaManager.Instance.GetSettingSFXVolume());
Destroy(berry);
UpdateStats(1, 0);
}
void DoPoisonBerry()
{
void DoPoisonBerry() {
AudioSource.PlayClipAtPoint(Resources.Load<AudioClip>("Sounds/Death"), Camera.main.transform.position, 1.2f * BazookaManager.Instance.GetSettingSFXVolume());
Respawn();
UpdateStats(0, 0);
}
void DoSlowBerry(GameObject berry)
{
void DoSlowBerry(GameObject berry) {
AudioSource.PlayClipAtPoint(Resources.Load<AudioClip>("Sounds/Downgrade"), Camera.main.transform.position, 0.35f * BazookaManager.Instance.GetSettingSFXVolume());
Destroy(berry);
boostLeft = 0f;
@@ -804,33 +636,27 @@ public class GamePlayer : MonoBehaviour
speedyLeft = 0f;
antiLeft = 0f;
goldenLeft = 0f;
if (score > 0)
{
if (score > 0) {
UpdateStats(-1, 0);
}
}
void DoUltraBerry(GameObject berry)
{
void DoUltraBerry(GameObject berry) {
AudioSource.PlayClipAtPoint(Resources.Load<AudioClip>("Sounds/Powerup"), Camera.main.transform.position, 0.35f * BazookaManager.Instance.GetSettingSFXVolume());
Destroy(berry);
speedyLeft = 0f;
antiLeft = 0f;
goldenLeft = 0f;
if (slownessLeft > 0f)
{
if (slownessLeft > 0f) {
slownessLeft = 0f;
UpdateStats(1, 0);
}
else
{
} else {
boostLeft += 10f;
UpdateStats(5, 0);
}
}
void DoSpeedyBerry(GameObject berry)
{
void DoSpeedyBerry(GameObject berry) {
AudioSource.PlayClipAtPoint(Resources.Load<AudioClip>("Sounds/SpeedyPowerup"), Camera.main.transform.position, 0.35f * BazookaManager.Instance.GetSettingSFXVolume());
Destroy(berry);
boostLeft = 0f;
@@ -841,16 +667,14 @@ public class GamePlayer : MonoBehaviour
UpdateStats(10, 0);
}
void DoCoinBerry(GameObject berry)
{
void DoCoinBerry(GameObject berry) {
AudioSource.PlayClipAtPoint(Resources.Load<AudioClip>("Sounds/CoinCollect"), Camera.main.transform.position, 0.35f * BazookaManager.Instance.GetSettingSFXVolume());
Destroy(berry);
totalCoins += 10;
UpdateStats(0, 0);
}
void DoAntiBerry(GameObject berry)
{
void DoAntiBerry(GameObject berry) {
AudioSource.PlayClipAtPoint(Resources.Load<AudioClip>("Sounds/Downgrade"), Camera.main.transform.position, 0.35f * BazookaManager.Instance.GetSettingSFXVolume());
Destroy(berry);
boostLeft = 0f;
@@ -861,8 +685,7 @@ public class GamePlayer : MonoBehaviour
UpdateStats(0, 0);
}
void DoGoldenBerry(GameObject berry)
{
void DoGoldenBerry(GameObject berry) {
AudioSource.PlayClipAtPoint(Resources.Load<AudioClip>("Sounds/Powerup"), Camera.main.transform.position, 0.35f * BazookaManager.Instance.GetSettingSFXVolume());
Destroy(berry);
boostLeft = 0f;
+16 -33
View File
@@ -3,8 +3,7 @@ using TMPro;
using UnityEngine;
using UnityEngine.UI;
public class GamePlayerPauseMenu : MonoBehaviour
{
public class GamePlayerPauseMenu : MonoBehaviour {
public static GamePlayerPauseMenu Instance;
[SerializeField] private Button backButton;
[SerializeField] private Button continueButton;
@@ -36,25 +35,20 @@ public class GamePlayerPauseMenu : MonoBehaviour
[SerializeField] private TMP_Text musicSliderText;
[SerializeField] private TMP_Text sfxSliderText;
void Awake()
{
void Awake() {
Instance = this;
continueButton.onClick.AddListener(GamePlayer.instance.DisablePause);
musicSlider.onValueChanged.AddListener(value =>
{
musicSlider.onValueChanged.AddListener(value => {
BazookaManager.Instance.SetSettingMusicVolume(value);
songLoop.volume = value;
});
sfxSlider.onValueChanged.AddListener(value =>
{
sfxSlider.onValueChanged.AddListener(value => {
BazookaManager.Instance.SetSettingSFXVolume(value);
});
editUiButton.onClick.AddListener(() =>
{
editUiButton.onClick.AddListener(() => {
ToggleEditingUI();
});
resetUiButton.onClick.AddListener(() =>
{
resetUiButton.onClick.AddListener(() => {
((RectTransform)scoreText.transform).anchoredPosition = new Vector2(0f, -70f);
((RectTransform)highScoreText.transform).anchoredPosition = new Vector2(0f, -140f);
((RectTransform)boostText.transform).anchoredPosition = new Vector2(0f, -190f);
@@ -65,8 +59,7 @@ public class GamePlayerPauseMenu : MonoBehaviour
PlayerPrefs.DeleteKey("DraggedUIBoostText");
PlayerPrefs.DeleteKey("DraggedUICoinsText");
PlayerPrefs.DeleteKey("DraggedUILevelText");
if (Application.isMobilePlatform)
{
if (Application.isMobilePlatform) {
((RectTransform)pauseButton.transform).anchoredPosition = new Vector2(128f, -128f);
((RectTransform)restartButton.transform).anchoredPosition = new Vector2(-128f, -128f);
((RectTransform)jumpButton.transform).anchoredPosition = new Vector2(-128f, 288f);
@@ -79,8 +72,7 @@ public class GamePlayerPauseMenu : MonoBehaviour
PlayerPrefs.DeleteKey("DraggedUILeftButton");
}
});
statsButton.onClick.AddListener(() =>
{
statsButton.onClick.AddListener(() => {
statsMenu.SetActive(true);
var text = new StringBuilder();
text.AppendLine("High Score: " + Tools.FormatWithCommas(BazookaManager.Instance.GetGameStoreHighScore()));
@@ -95,49 +87,41 @@ public class GamePlayerPauseMenu : MonoBehaviour
text.AppendLine("Total Attempts: " + Tools.FormatWithCommas(BazookaManager.Instance.GetGameStoreTotalAttepts()));
statsText.text = text.ToString();
});
statsMenuExitButton.onClick.AddListener(() =>
{
statsMenuExitButton.onClick.AddListener(() => {
statsMenu.SetActive(false);
statsText.text = string.Empty;
});
musicSlider.value = BazookaManager.Instance.GetSettingMusicVolume();
sfxSlider.value = BazookaManager.Instance.GetSettingSFXVolume();
if (!Application.isMobilePlatform)
{
if (!Application.isMobilePlatform) {
settingFullscreenToggle.isOn = BazookaManager.Instance.GetSettingFullScreen() == true;
settingVSyncToggle.isOn = BazookaManager.Instance.GetSettingVsync() == true;
settingRandomMusicToggle.isOn = BazookaManager.Instance.GetSettingRandomMusic() == true;
settingFullscreenToggle.onValueChanged.AddListener(value =>
{
settingFullscreenToggle.onValueChanged.AddListener(value => {
BazookaManager.Instance.SetSettingFullScreen(value);
var width = Display.main.systemWidth;
var height = Display.main.systemHeight;
Screen.SetResolution(width, height, value);
});
settingVSyncToggle.onValueChanged.AddListener(value =>
{
settingVSyncToggle.onValueChanged.AddListener(value => {
BazookaManager.Instance.SetSettingVsync(value);
QualitySettings.vSyncCount = value ? 1 : -1;
});
}
else
{
} else {
settingFullscreenToggle.interactable = false;
settingVSyncToggle.interactable = false;
settingRandomMusicToggle.isOn = BazookaManager.Instance.GetSettingRandomMusic() == true;
}
settingRandomMusicToggle.onValueChanged.AddListener(value => BazookaManager.Instance.SetSettingRandomMusic(value));
musicSlider.onValueChanged.AddListener(value =>
{
musicSlider.onValueChanged.AddListener(value => {
BazookaManager.Instance.SetSettingMusicVolume(value);
GamePlayer.instance.backgroundMusic.volume = value;
});
sfxSlider.onValueChanged.AddListener(value => BazookaManager.Instance.SetSettingSFXVolume(value));
}
public void ToggleEditingUI()
{
public void ToggleEditingUI() {
editingUI = !editingUI;
musicSlider.gameObject.SetActive(!musicSlider.gameObject.activeSelf);
sfxSlider.gameObject.SetActive(!sfxSlider.gameObject.activeSelf);
@@ -156,8 +140,7 @@ public class GamePlayerPauseMenu : MonoBehaviour
boostText.GetComponent<DraggableUI>().canDrag = !boostText.GetComponent<DraggableUI>().canDrag;
coinsText.GetComponent<DraggableUI>().canDrag = !coinsText.GetComponent<DraggableUI>().canDrag;
levelText.GetComponent<DraggableUI>().canDrag = !levelText.GetComponent<DraggableUI>().canDrag;
if (Application.isMobilePlatform)
{
if (Application.isMobilePlatform) {
var pauseDraggableUI = pauseButton.GetComponent<DraggableUI>();
var restartDraggableUI = restartButton.GetComponent<DraggableUI>();
var jumpDraggableUI = jumpButton.GetComponent<DraggableUI>();
+7 -14
View File
@@ -2,17 +2,14 @@ using TMPro;
using UnityEngine;
[RequireComponent(typeof(TMP_Text))]
public class GlobalFPSText : MonoBehaviour
{
public class GlobalFPSText : MonoBehaviour {
private TMP_Text text;
private float timer;
private int frames;
private float fps;
void Awake()
{
if (FindObjectsByType<GlobalFPSText>(FindObjectsSortMode.None).Length > 1)
{
void Awake() {
if (FindObjectsByType<GlobalFPSText>(FindObjectsSortMode.None).Length > 1) {
Destroy(gameObject.transform.parent.gameObject);
return;
}
@@ -20,19 +17,15 @@ public class GlobalFPSText : MonoBehaviour
text = GetComponent<TMP_Text>();
}
void Update()
{
void Update() {
var enabled = BazookaManager.Instance.GetSettingShowFPS();
if (!enabled && text.text != "")
{
if (!enabled && text.text != "") {
text.text = "";
return;
}
else if (!enabled) return;
} else if (!enabled) return;
frames++;
timer += Time.unscaledDeltaTime;
if (timer >= 0.25f)
{
if (timer >= 0.25f) {
fps = frames / timer;
text.text = "FPS: " + Mathf.RoundToInt(fps);
frames = 0;
+4 -8
View File
@@ -1,21 +1,17 @@
using UnityEngine;
public class HideIfSettingFalse : MonoBehaviour
{
public class HideIfSettingFalse : MonoBehaviour {
[SerializeField] private SettingTypes setting;
[SerializeField] private bool reverse;
void Start()
{
void Start() {
bool value = GetSettingValue(setting);
gameObject.SetActive(value == !reverse);
}
bool GetSettingValue(SettingTypes s)
{
bool GetSettingValue(SettingTypes s) {
var b = BazookaManager.Instance;
return s switch
{
return s switch {
SettingTypes.FullScreen => b.GetSettingFullScreen(),
SettingTypes.ShowFPS => b.GetSettingShowFPS(),
SettingTypes.Vsync => b.GetSettingVsync(),
+3 -6
View File
@@ -1,17 +1,14 @@
using UnityEngine;
using UnityEngine.EventSystems;
public class HoldableButton : MonoBehaviour, IPointerDownHandler, IPointerUpHandler
{
public class HoldableButton : MonoBehaviour, IPointerDownHandler, IPointerUpHandler {
public bool isPressed;
public void OnPointerDown(PointerEventData eventData)
{
public void OnPointerDown(PointerEventData eventData) {
isPressed = true;
}
public void OnPointerUp(PointerEventData eventData)
{
public void OnPointerUp(PointerEventData eventData) {
isPressed = false;
}
}
@@ -10,8 +10,7 @@ using UnityEngine;
using UnityEngine.Networking;
using UnityEngine.UI;
public class IconMarketplaceDownloadIcon : MonoBehaviour
{
public class IconMarketplaceDownloadIcon : MonoBehaviour {
private readonly static WaitForSeconds _waitForSeconds2 = new(2f);
[SerializeField] private IconMarketplaceManager marketplaceManager;
[SerializeField] private TMP_Text statusText;
@@ -45,8 +44,7 @@ public class IconMarketplaceDownloadIcon : MonoBehaviour
internal bool anyChanges = false;
void Awake()
{
void Awake() {
optionsPanelPriceRangeMinInput.onSelect.AddListener((_) => optionsPanelPriceRangeMinInput.caretPosition = optionsPanelPriceRangeMinInput.text.Length);
optionsPanelPriceRangeMaxInput.onSelect.AddListener((_) => optionsPanelPriceRangeMaxInput.caretPosition = optionsPanelPriceRangeMaxInput.text.Length);
optionsPanelSearchForInputField.onSelect.AddListener((_) => optionsPanelSearchForInputField.caretPosition = optionsPanelSearchForInputField.text.Length);
@@ -54,87 +52,72 @@ public class IconMarketplaceDownloadIcon : MonoBehaviour
backButton.onClick.AddListener(() => marketplaceManager.SwitchPanel(0));
refreshButton.onClick.AddListener(GetIcons);
optionsButton.onClick.AddListener(() => optionsPanel.SetActive(true));
optionsPanelSubmitButton.onClick.AddListener(() =>
{
optionsPanelSubmitButton.onClick.AddListener(() => {
optionsPanel.SetActive(false);
if (anyChanges)
{
if (anyChanges) {
anyChanges = false;
GetIcons();
}
});
optionsPanelResetButton.onClick.AddListener(() =>
{
optionsPanelResetButton.onClick.AddListener(() => {
optionsPanelSortByDropdown.value = 3;
optionsPanelPriceRangeToggle.isOn = false;
optionsPanelSearchForToggle.isOn = false;
optionsPanelOnlyShowToggle.isOn = false;
});
optionsPanelPriceRangeToggle.onValueChanged.AddListener((on) =>
{
optionsPanelPriceRangeToggle.onValueChanged.AddListener((on) => {
anyChanges = true;
if (!on)
{
if (!on) {
optionsPanelPriceRangeMinInput.text = "10";
optionsPanelPriceRangeMaxInput.text = "250";
}
optionsPanelPriceRangeMinInput.interactable = on;
optionsPanelPriceRangeMaxInput.interactable = on;
});
optionsPanelSearchForToggle.onValueChanged.AddListener((on) =>
{
optionsPanelSearchForToggle.onValueChanged.AddListener((on) => {
anyChanges = true;
if (!on) optionsPanelSearchForInputField.text = "";
optionsPanelSearchForInputField.interactable = on;
});
optionsPanelOnlyShowToggle.onValueChanged.AddListener((on) =>
{
optionsPanelOnlyShowToggle.onValueChanged.AddListener((on) => {
anyChanges = true;
if (!on) optionsPanelOnlyShowDropdown.value = 0;
optionsPanelOnlyShowDropdown.interactable = on;
});
optionsPanelSortByDropdown.onValueChanged.AddListener((_) => anyChanges = true);
optionsPanelPriceRangeMinInput.onValueChanged.AddListener((value) =>
{
optionsPanelPriceRangeMinInput.onValueChanged.AddListener((value) => {
anyChanges = true;
priceRangeMin = value;
});
optionsPanelPriceRangeMaxInput.onValueChanged.AddListener((value) =>
{
optionsPanelPriceRangeMaxInput.onValueChanged.AddListener((value) => {
anyChanges = true;
priceRangeMax = value;
});
optionsPanelSearchForInputField.onValueChanged.AddListener((value) =>
{
optionsPanelSearchForInputField.onValueChanged.AddListener((value) => {
anyChanges = true;
searchForValue = value;
});
optionsPanelOnlyShowDropdown.onValueChanged.AddListener((_) => anyChanges = true);
}
internal void Load()
{
internal void Load() {
GetIcons();
balanceText.text = Tools.FormatWithCommas(BazookaManager.Instance.GetCustomBirdIconData().Balance);
}
internal async void GetIcons()
{
internal async void GetIcons() {
refreshButton.interactable = false;
optionsButton.interactable = false;
backButton.interactable = false;
foreach (Transform item in content.transform)
{
if (item.gameObject.activeSelf)
{
foreach (Transform item in content.transform) {
if (item.gameObject.activeSelf) {
Destroy(item.gameObject);
}
}
var currentIcons = new JArray();
foreach (var icon in BazookaManager.Instance.GetCustomBirdIconData().Purchased)
{
foreach (var icon in BazookaManager.Instance.GetCustomBirdIconData().Purchased) {
currentIcons.Add(icon);
}
ShowStatus("Loading...");
@@ -154,8 +137,7 @@ public class IconMarketplaceDownloadIcon : MonoBehaviour
request.SetRequestHeader("ClientVersion", Application.version);
request.SetRequestHeader("ClientPlatform", Application.platform.ToString());
await request.SendWebRequest();
if (request.downloadHandler.text == null)
{
if (request.downloadHandler.text == null) {
refreshButton.interactable = true;
optionsButton.interactable = true;
backButton.interactable = true;
@@ -166,8 +148,7 @@ public class IconMarketplaceDownloadIcon : MonoBehaviour
var jsonResponse = JObject.Parse(request.downloadHandler.text);
var icons = JsonConvert.DeserializeObject<MarketplaceTempIcon[]>(jsonResponse["data"].ToString());
var localUserID = BazookaManager.Instance.GetAccountID();
foreach (var entry in icons)
{
foreach (var entry in icons) {
GameObject newIcon = Instantiate(sample, content.transform);
newIcon.name = "IconEntry";
newIcon.transform.GetChild(0).GetChild(0).gameObject.AddComponent<WaitingForCustomIcon>().ID = entry.ID;
@@ -181,31 +162,25 @@ public class IconMarketplaceDownloadIcon : MonoBehaviour
var sellBtn = BtnGrid.transform.GetChild(1).GetComponent<Button>();
var sellBtnText = sellBtn.transform.GetChild(0).GetComponent<TMP_Text>();
sellBtn.onClick.AddListener(() =>
{
sellBtn.onClick.AddListener(() => {
HandleSell(entry, buyBtn, buyBtnText, sellBtn, localUserID);
Tools.RefreshHierarchy(newIcon);
});
buyBtn.onClick.AddListener(() =>
{
buyBtn.onClick.AddListener(() => {
HandlePurchase(entry, buyBtn, sellBtn, localUserID);
Tools.RefreshHierarchy(newIcon);
});
bool alreadyBought = BazookaManager.Instance.GetCustomBirdIconData().Purchased.Any(d => d == entry.ID);
if (alreadyBought)
{
if (alreadyBought) {
buyBtn.interactable = false;
sellBtn.gameObject.SetActive(true);
if (localUserID != entry.CreatorUserID)
buyBtnText.text = "Purchased";
else
{
else {
buyBtnText.text = "Claimed";
sellBtnText.text = "Unclaim";
}
}
else
{
} else {
if (localUserID != entry.CreatorUserID) buyBtnText.text = "Purchase";
else buyBtnText.text = "Claim";
}
@@ -219,14 +194,11 @@ public class IconMarketplaceDownloadIcon : MonoBehaviour
backButton.interactable = true;
}
void HandlePurchase(MarketplaceTempIcon data, Button button, Button sellButton, BigInteger? localUserID)
{
void HandlePurchase(MarketplaceTempIcon data, Button button, Button sellButton, BigInteger? localUserID) {
button.interactable = false;
MarketplaceIconStorageType marketplaceIconStorage = BazookaManager.Instance.GetCustomBirdIconData();
if (localUserID != data.CreatorUserID)
{
if (data.Price > marketplaceIconStorage.Balance)
{
if (localUserID != data.CreatorUserID) {
if (data.Price > marketplaceIconStorage.Balance) {
button.interactable = true;
ShowStatus("You can't afford this icon! You need " + Tools.FormatWithCommas(data.Price - marketplaceIconStorage.Balance) + " more coins");
return;
@@ -237,12 +209,9 @@ public class IconMarketplaceDownloadIcon : MonoBehaviour
}
marketplaceIconStorage.Purchased.Add(data.ID);
sellButton.gameObject.SetActive(true);
if (localUserID != data.CreatorUserID)
{
if (localUserID != data.CreatorUserID) {
button.transform.GetChild(0).GetComponent<TMP_Text>().text = "Purchased";
}
else
{
} else {
button.transform.GetChild(0).GetComponent<TMP_Text>().text = "Claimed";
sellButton.transform.GetChild(0).GetComponent<TMP_Text>().text = "Unclaim";
}
@@ -250,15 +219,12 @@ public class IconMarketplaceDownloadIcon : MonoBehaviour
BazookaManager.Instance.SetCustomBirdIconData(marketplaceIconStorage);
}
void HandleSell(MarketplaceTempIcon data, Button buyBtn, TMP_Text buyBtnText, Button sellButton, BigInteger? localUserID)
{
void HandleSell(MarketplaceTempIcon data, Button buyBtn, TMP_Text buyBtnText, Button sellButton, BigInteger? localUserID) {
MarketplaceIconStorageType marketplaceIconStorage = BazookaManager.Instance.GetCustomBirdIconData();
var owned = marketplaceIconStorage.Purchased.Contains(data.ID);
if (owned)
{
if (owned) {
marketplaceIconStorage.Purchased.Remove(data.ID);
if (data.CreatorUserID != (BazookaManager.Instance.GetAccountID() ?? 0))
{
if (data.CreatorUserID != (BazookaManager.Instance.GetAccountID() ?? 0)) {
marketplaceIconStorage.Balance += data.Price;
iconPurchaseSound.Stop();
iconPurchaseSound.Play();
@@ -267,8 +233,7 @@ public class IconMarketplaceDownloadIcon : MonoBehaviour
balanceText.text = Tools.FormatWithCommas(marketplaceIconStorage.Balance);
BazookaManager.Instance.SetCustomBirdIconData(marketplaceIconStorage);
if (localUserID != data.CreatorUserID) buyBtnText.text = "Purchase";
else
{
else {
buyBtnText.text = "Claim";
buyBtnText.text = "Claim";
}
@@ -277,10 +242,8 @@ public class IconMarketplaceDownloadIcon : MonoBehaviour
}
}
void ShowStatus(string content)
{
if (content == null)
{
void ShowStatus(string content) {
if (content == null) {
if (statusRoutine != null) StopCoroutine(statusRoutine);
statusText.gameObject.SetActive(false);
statusText.text = "";
@@ -290,15 +253,13 @@ public class IconMarketplaceDownloadIcon : MonoBehaviour
statusRoutine = StartCoroutine(StatusRoutine());
}
IEnumerator StatusRoutine()
{
IEnumerator StatusRoutine() {
statusText.gameObject.SetActive(true);
statusText.text = statusMessage;
statusText.color = new Color(statusText.color.r, statusText.color.g, statusText.color.b, 0f);
float t = 0f;
while (t < 0.5f)
{
while (t < 0.5f) {
t += Time.deltaTime;
float a = t / 0.5f;
statusText.color = new Color(statusText.color.r, statusText.color.g, statusText.color.b, a);
@@ -308,8 +269,7 @@ public class IconMarketplaceDownloadIcon : MonoBehaviour
yield return _waitForSeconds2;
t = 0f;
while (t < 0.5f)
{
while (t < 0.5f) {
t += Time.deltaTime;
float a = 1f - (t / 0.5f);
statusText.color = new Color(statusText.color.r, statusText.color.g, statusText.color.b, a);
@@ -5,8 +5,7 @@ using UnityEngine.InputSystem;
using UnityEngine.SceneManagement;
using UnityEngine.UI;
public class IconMarketplaceManager : MonoBehaviour
{
public class IconMarketplaceManager : MonoBehaviour {
[SerializeField] private GameObject normalPanel;
[SerializeField] private GameObject downloadPanel;
[SerializeField] private GameObject uploadPanel;
@@ -18,16 +17,12 @@ public class IconMarketplaceManager : MonoBehaviour
[SerializeField] private Button uploadButton;
[SerializeField] private TMP_Text coinText;
void Start()
{
void Start() {
downloadPanelScript.iconPurchaseSound.volume = BazookaManager.Instance.GetSettingSFXVolume();
downloadButton.onClick.AddListener(() => SwitchPanel(1));
if (BazookaManager.Instance.GetAccountID() != null && BazookaManager.Instance.GetAccountName() != null && BazookaManager.Instance.GetAccountSession() != null)
{
if (BazookaManager.Instance.GetAccountID() != null && BazookaManager.Instance.GetAccountName() != null && BazookaManager.Instance.GetAccountSession() != null) {
uploadButton.onClick.AddListener(() => SwitchPanel(2));
}
else
{
} else {
uploadButton.interactable = false;
uploadButton.transform.GetChild(0).transform.localPosition = new Vector3(0, 10, 0);
uploadButton.transform.GetChild(1).GetComponent<TMP_Text>().text = "Not logged in to an account";
@@ -35,15 +30,13 @@ public class IconMarketplaceManager : MonoBehaviour
SwitchPanel(0);
}
internal void SwitchPanel(int panelIndex)
{
internal void SwitchPanel(int panelIndex) {
downloadPanelScript.iconPurchaseSound.Stop();
downloadPanelScript.anyChanges = false;
downloadPanelScript.optionsPanelSortByDropdown.value = 3;
downloadPanelScript.optionsPanelPriceRangeToggle.isOn = false;
downloadPanelScript.optionsPanelSearchForToggle.isOn = false;
switch (panelIndex)
{
switch (panelIndex) {
case 0:
coinText.text = "You have " + Tools.FormatWithCommas(BazookaManager.Instance.GetCustomBirdIconData().Balance) + " coins";
normalPanel.SetActive(true);
@@ -52,10 +45,8 @@ public class IconMarketplaceManager : MonoBehaviour
if (DiscordRPCHandler.Instance != null) DiscordRPCHandler.Instance.UpdateRPC("Choosing what to do in the icon marketplace", null);
break;
case 1:
foreach (Transform item in downloadPanelScript.content.transform)
{
if (item.gameObject.activeSelf)
{
foreach (Transform item in downloadPanelScript.content.transform) {
if (item.gameObject.activeSelf) {
Destroy(item.gameObject);
}
}
@@ -75,15 +66,12 @@ public class IconMarketplaceManager : MonoBehaviour
}
}
async void Update()
{
if (Keyboard.current.escapeKey.wasPressedThisFrame)
{
async void Update() {
if (Keyboard.current.escapeKey.wasPressedThisFrame) {
if (downloadPanelScript.optionsPanel.activeSelf) downloadPanelScript.optionsPanelSubmitButton.onClick.Invoke();
else if (uploadPanel.activeSelf && FileBrowser.IsOpen) return;
else if (downloadPanel.activeSelf || uploadPanel.activeSelf) SwitchPanel(0);
else await SceneManager.LoadSceneAsync("MainMenu");
}
else if (Keyboard.current.rKey.wasPressedThisFrame && downloadPanel.activeSelf && downloadPanelScript.refreshButton.interactable) downloadPanelScript.GetIcons();
} else if (Keyboard.current.rKey.wasPressedThisFrame && downloadPanel.activeSelf && downloadPanelScript.refreshButton.interactable) downloadPanelScript.GetIcons();
}
}
@@ -8,8 +8,7 @@ using UnityEngine;
using UnityEngine.Networking;
using UnityEngine.UI;
public class IconMarketplaceUploadIcon : MonoBehaviour
{
public class IconMarketplaceUploadIcon : MonoBehaviour {
[SerializeField] private IconMarketplaceManager marketplaceManager;
[SerializeField] private TMP_Text statusText;
[SerializeField] private Button backButton;
@@ -22,42 +21,30 @@ public class IconMarketplaceUploadIcon : MonoBehaviour
[SerializeField] private GameObject birdImageNone;
private string birdData = null;
void Awake()
{
void Awake() {
verifyCodeInput.onSelect.AddListener((_) => verifyCodeInput.caretPosition = verifyCodeInput.text.Length);
birdPriceInput.onSelect.AddListener((_) => birdPriceInput.caretPosition = birdPriceInput.text.Length);
birdNameInput.onSelect.AddListener((_) => birdNameInput.caretPosition = birdNameInput.text.Length);
backButton.onClick.AddListener(() => marketplaceManager.SwitchPanel(0));
uploadButton.onClick.AddListener(() =>
{
if (birdPriceInput.text.Trim() == string.Empty)
{
uploadButton.onClick.AddListener(() => {
if (birdPriceInput.text.Trim() == string.Empty) {
Tools.UpdateStatusText(statusText, "Bird price can't be empty", Color.red);
}
else if (birdNameInput.text.Trim() == string.Empty)
{
} else if (birdNameInput.text.Trim() == string.Empty) {
Tools.UpdateStatusText(statusText, "Bird name can't be empty", Color.red);
}
else if (birdData == null)
{
} else if (birdData == null) {
Tools.UpdateStatusText(statusText, "You must upload an image", Color.red);
}
else
{
} else {
UploadIcon();
}
});
selectButton.onClick.AddListener(async () =>
{
selectButton.onClick.AddListener(async () => {
string path = await OpenFilePicker();
if (path == null) return;
byte[] fileContent;
try
{
try {
fileContent = File.ReadAllBytes(path);
if (fileContent.Length > 1024 * 1024)
{
if (fileContent.Length > 1024 * 1024) {
Tools.UpdateStatusText(statusText, "File size exceeds 1 MB limit", Color.red);
return;
}
@@ -66,16 +53,14 @@ public class IconMarketplaceUploadIcon : MonoBehaviour
birdImageNone.SetActive(false);
birdImage.gameObject.SetActive(true);
}
catch (Exception e)
{
catch (Exception e) {
Tools.UpdateStatusText(statusText, "Failed to read file: " + e.Message, Color.red);
return;
}
});
}
async Task<string> OpenFilePicker()
{
async Task<string> OpenFilePicker() {
FileBrowser.SetFilters(true, new FileBrowser.Filter("Images", ".png"));
var tcs = new TaskCompletionSource<string>();
@@ -90,8 +75,7 @@ public class IconMarketplaceUploadIcon : MonoBehaviour
return await tcs.Task;
}
async void UploadIcon()
{
async void UploadIcon() {
uploadButton.interactable = false;
backButton.interactable = false;
selectButton.interactable = false;
@@ -106,8 +90,7 @@ public class IconMarketplaceUploadIcon : MonoBehaviour
request.SetRequestHeader("ClientVersion", Application.version);
request.SetRequestHeader("ClientPlatform", Application.platform.ToString());
await request.SendWebRequest();
if (request.downloadHandler.text == null)
{
if (request.downloadHandler.text == null) {
uploadButton.interactable = true;
backButton.interactable = true;
selectButton.interactable = true;
@@ -122,8 +105,7 @@ public class IconMarketplaceUploadIcon : MonoBehaviour
selectButton.interactable = true;
}
internal void Reset()
{
internal void Reset() {
birdImage.sprite = null;
birdImageNone.SetActive(true);
birdImage.gameObject.SetActive(false);
+31 -62
View File
@@ -7,8 +7,7 @@ using UnityEngine.InputSystem;
using UnityEngine.SceneManagement;
using UnityEngine.UI;
public class Iconsmenu : MonoBehaviour
{
public class Iconsmenu : MonoBehaviour {
[SerializeField] private GameObject iconsPanel;
[SerializeField] private GameObject overlaysPanel;
[SerializeField] private GameObject marketplaceIconsPanel;
@@ -26,11 +25,9 @@ public class Iconsmenu : MonoBehaviour
[SerializeField] private ColorPanel overlayColorPanel;
private readonly Dictionary<string, Button> customIcons = new();
private void Start()
{
private void Start() {
var customIconData = BazookaManager.Instance.GetCustomBirdIconData();
foreach (var icon in customIconData.Purchased)
{
foreach (var icon in customIconData.Purchased) {
var iconEntry = Instantiate(marketplaceIconsSample, marketplaceIconsContent.transform);
iconEntry.name = "MarketplaceIcon";
var button = iconEntry.GetComponent<Button>();
@@ -40,8 +37,7 @@ public class Iconsmenu : MonoBehaviour
iconEntry.SetActive(true);
}
iconColorPanel.Init(customIconData.Selected == null ? BazookaManager.Instance.GetColorSettingIcon() : JArray.Parse("[255,255,255]"), Color.white);
iconColorPanel.OnColorChanged += color =>
{
iconColorPanel.OnColorChanged += color => {
BazookaManager.Instance.SetColorSettingIcon(color);
foreach (var icon in icons)
icon.transform.GetChild(0).GetComponent<Image>().color = new Color(
@@ -51,11 +47,9 @@ public class Iconsmenu : MonoBehaviour
);
};
overlayColorPanel.Init(customIconData.Selected == null ? BazookaManager.Instance.GetColorSettingOverlay() : JArray.Parse("[255,255,255]"), Color.white);
overlayColorPanel.OnColorChanged += color =>
{
overlayColorPanel.OnColorChanged += color => {
BazookaManager.Instance.SetColorSettingOverlay(color);
foreach (var overlay in overlays)
{
foreach (var overlay in overlays) {
var img = overlay.transform.GetChild(0).TryGetComponent<Image>(out var image) ? image : null;
if (img == null) continue;
@@ -67,8 +61,7 @@ public class Iconsmenu : MonoBehaviour
}
};
if (customIconData.Selected == null)
{
if (customIconData.Selected == null) {
defaultIcon = Tools.GetIconForUser(BazookaManager.Instance.GetAccountID() ?? 0);
icons[0].transform.GetChild(0).GetComponent<Image>().sprite = defaultIcon;
@@ -76,34 +69,28 @@ public class Iconsmenu : MonoBehaviour
SelectOverlay(BazookaManager.Instance.GetBirdOverlay());
SelectIcon(BazookaManager.Instance.GetBirdIcon());
if (BazookaManager.Instance.GetBirdIcon() == 7)
{
if (BazookaManager.Instance.GetBirdIcon() == 7) {
SelectOverlay(0);
placeholderButton.interactable = false;
}
}
else SwitchToMarketplaceIcons();
} else SwitchToMarketplaceIcons();
placeholderButton.onClick.AddListener(ToggleKit);
previewBird.GetComponentInParent<Button>().onClick.AddListener(() =>
{
previewBird.GetComponentInParent<Button>().onClick.AddListener(() => {
var scale = previewBird.transform.localScale;
scale.x = scale.x == -1 ? 1 : -1;
previewBird.transform.localScale = scale;
});
for (int i = 0; i < icons.Length; i++)
{
for (int i = 0; i < icons.Length; i++) {
int index = i;
icons[i].onClick.AddListener(() => SelectIcon(index + 1));
}
for (int i = 0; i < overlays.Length; i++)
{
for (int i = 0; i < overlays.Length; i++) {
int index = i;
overlays[i].onClick.AddListener(() => SelectOverlay(index));
}
}
private void SwitchToIcon()
{
private void SwitchToIcon() {
iconsPanel.SetActive(true);
overlaysPanel.SetActive(false);
marketplaceIconsPanel.SetActive(false);
@@ -113,8 +100,7 @@ public class Iconsmenu : MonoBehaviour
overlayColorPanel.gameObject.SetActive(true);
}
private void SwitchToOverlay()
{
private void SwitchToOverlay() {
iconsPanel.SetActive(false);
overlaysPanel.SetActive(true);
marketplaceIconsPanel.SetActive(false);
@@ -122,8 +108,7 @@ public class Iconsmenu : MonoBehaviour
placeholderButton.GetComponentInChildren<TMP_Text>().text = "Marketplace";
}
private void SwitchToMarketplaceIcons()
{
private void SwitchToMarketplaceIcons() {
iconsPanel.SetActive(false);
overlaysPanel.SetActive(false);
marketplaceIconsPanel.SetActive(true);
@@ -134,8 +119,7 @@ public class Iconsmenu : MonoBehaviour
var customIconData = BazookaManager.Instance.GetCustomBirdIconData();
foreach (var btn in customIcons.Values) btn.interactable = true;
if (customIconData.Selected != null)
foreach (var icon in customIconData.Purchased)
{
foreach (var icon in customIconData.Purchased) {
if (icon == customIconData.Selected) SelectCustomIcon(icon, false);
customIcons[icon].interactable = icon != customIconData.Selected;
}
@@ -143,12 +127,10 @@ public class Iconsmenu : MonoBehaviour
RenderIcons();
}
private void ToggleKit()
{
private void ToggleKit() {
if (GetCurrentKit() == 1) SwitchToOverlay();
else if (GetCurrentKit() == 2) SwitchToMarketplaceIcons();
else if (GetCurrentKit() == 3)
{
else if (GetCurrentKit() == 3) {
defaultIcon = Tools.GetIconForUser(BazookaManager.Instance.GetAccountID() ?? 0);
icons[0].transform.GetChild(0).GetComponent<Image>().sprite = defaultIcon;
@@ -158,24 +140,21 @@ public class Iconsmenu : MonoBehaviour
iconColorPanel.SetColor(BazookaManager.Instance.GetColorSettingIcon());
overlayColorPanel.SetColor(BazookaManager.Instance.GetColorSettingOverlay());
if (BazookaManager.Instance.GetBirdIcon() == 7)
{
if (BazookaManager.Instance.GetBirdIcon() == 7) {
SelectOverlay(0);
placeholderButton.interactable = false;
}
}
}
private int GetCurrentKit()
{
private int GetCurrentKit() {
if (iconsPanel.activeSelf) return 1;
else if (overlaysPanel.activeSelf) return 2;
else if (marketplaceIconsPanel.activeSelf) return 3;
return 0;
}
private void SelectIcon(int iconID)
{
private void SelectIcon(int iconID) {
var customData = BazookaManager.Instance.GetCustomBirdIconData();
customData.Selected = null;
BazookaManager.Instance.SetCustomBirdIconData(customData);
@@ -184,22 +163,18 @@ public class Iconsmenu : MonoBehaviour
icons[i].interactable = iconID != i + 1;
previewBird.sprite = Resources.Load<Sprite>("Icons/Icons/bird_" + iconID);
if (iconID == 1) previewBird.sprite = defaultIcon;
if (iconID == 7)
{
if (iconID == 7) {
SelectOverlay(0);
placeholderButton.interactable = false;
}
else placeholderButton.interactable = true;
} else placeholderButton.interactable = true;
}
private void SelectOverlay(int overlayID)
{
private void SelectOverlay(int overlayID) {
var customData = BazookaManager.Instance.GetCustomBirdIconData();
customData.Selected = null;
BazookaManager.Instance.SetCustomBirdIconData(customData);
BazookaManager.Instance.SetBirdOverlay(overlayID);
for (int i = 0; i < overlays.Length; i++)
{
for (int i = 0; i < overlays.Length; i++) {
overlays[i].interactable = overlayID != i;
}
previewOverlay.rectTransform.localPosition = new Vector3(-32f, 44.50001f, 0f);
@@ -208,16 +183,13 @@ public class Iconsmenu : MonoBehaviour
else if (overlayID == 11) previewOverlay.rectTransform.localPosition = new Vector3(-31.44f, 43.50004f, 0f);
else if (overlayID == 13) previewOverlay.rectTransform.localPosition = new Vector3(-35.28575f, 31.3667f, 0f);
if (overlayID == 0)
{
if (overlayID == 0) {
previewOverlay.gameObject.SetActive(false);
previewOverlay.sprite = null;
}
else previewOverlay.sprite = Resources.Load<Sprite>("Icons/Overlays/overlay_" + overlayID);
} else previewOverlay.sprite = Resources.Load<Sprite>("Icons/Overlays/overlay_" + overlayID);
}
void SelectCustomIcon(string icon, bool renderIcons = true)
{
void SelectCustomIcon(string icon, bool renderIcons = true) {
var customData = BazookaManager.Instance.GetCustomBirdIconData();
customData.Selected = icon;
BazookaManager.Instance.SetCustomBirdIconData(customData);
@@ -227,19 +199,16 @@ public class Iconsmenu : MonoBehaviour
previewOverlay.gameObject.SetActive(false);
previewOverlay.sprite = null;
previewOverlay.color = Color.white;
foreach (var loopIcon in customData.Purchased)
{
foreach (var loopIcon in customData.Purchased) {
customIcons[loopIcon].interactable = loopIcon != icon;
}
}
async void Update()
{
async void Update() {
if (Keyboard.current.escapeKey.wasPressedThisFrame) await SceneManager.LoadSceneAsync("MainMenu");
}
void RenderIcons()
{
void RenderIcons() {
var objects = FindObjectsByType<WaitingForCustomIcon>(FindObjectsSortMode.None);
if (objects.Length != 0) CustomIconLoader.Init(objects);
}
+1 -2
View File
@@ -1,6 +1,5 @@
using UnityEngine;
public class IgnoreRaycast : MonoBehaviour, ICanvasRaycastFilter
{
public class IgnoreRaycast : MonoBehaviour, ICanvasRaycastFilter {
public bool IsRaycastLocationValid(Vector2 sp, Camera eventCamera) => GetComponent<DraggableUI>() != null && GetComponent<DraggableUI>().canDrag;
}
+36 -75
View File
@@ -7,8 +7,7 @@ using UnityEngine.Networking;
using UnityEngine.SceneManagement;
using UnityEngine.UI;
public class LeaderboardsMenu : MonoBehaviour
{
public class LeaderboardsMenu : MonoBehaviour {
[SerializeField] private TMP_Text statusText;
[SerializeField] private Button backButton;
[SerializeField] private Button refreshButton;
@@ -31,8 +30,7 @@ public class LeaderboardsMenu : MonoBehaviour
private LeaderboardMode mode = LeaderboardMode.None;
private bool changedByCode = false;
void Awake()
{
void Awake() {
selectionScoreButton.onClick.AddListener(() => { mode = LeaderboardMode.Score; SwitchMenu(1); });
selectionBerryButton.onClick.AddListener(() => { mode = LeaderboardMode.Berry; SwitchMenu(1); });
selectionCoinButton.onClick.AddListener(() => { mode = LeaderboardMode.Coin; SwitchMenu(1); });
@@ -42,37 +40,29 @@ public class LeaderboardsMenu : MonoBehaviour
selectionTotalBerriesButton.onClick.AddListener(() => { mode = LeaderboardMode.TotalBerries; SwitchMenu(1); });
berryShowTypeDropdown.onValueChanged.AddListener(_ => GetTopPlayers());
backButton.onClick.AddListener(async () =>
{
backButton.onClick.AddListener(async () => {
if (selectionPanel.activeSelf) await SceneManager.LoadSceneAsync("MainMenu");
else if (scoresPanel.activeSelf) SwitchMenu(0);
});
refreshButton.onClick.AddListener(GetTopPlayers);
}
void SwitchMenu(int menu)
{
void SwitchMenu(int menu) {
UpdateStatus(false, "");
if (!selectionPanel.activeSelf)
{
foreach (Transform item in content.transform)
{
if (item.gameObject.activeSelf)
{
if (!selectionPanel.activeSelf) {
foreach (Transform item in content.transform) {
if (item.gameObject.activeSelf) {
Destroy(item.gameObject);
}
}
}
if (menu == 0)
{
if (menu == 0) {
mode = LeaderboardMode.None;
refreshButton.gameObject.SetActive(false);
selectionPanel.SetActive(true);
scoresPanel.SetActive(false);
}
else if (menu == 1)
{
} else if (menu == 1) {
refreshButton.transform.localPosition = mode == LeaderboardMode.Berry ? new Vector2(402.5f, 282.33f) : new Vector2(-402.5f, -282.33f);
refreshButton.gameObject.SetActive(true);
berryShowTypeDropdown.gameObject.SetActive(mode == LeaderboardMode.Berry);
@@ -85,15 +75,12 @@ public class LeaderboardsMenu : MonoBehaviour
}
}
async void GetTopPlayers()
{
async void GetTopPlayers() {
if (changedByCode) return;
backButton.interactable = false;
refreshButton.interactable = false;
foreach (Transform item in content.transform)
{
if (item.gameObject.activeSelf)
{
foreach (Transform item in content.transform) {
if (item.gameObject.activeSelf) {
Destroy(item.gameObject);
}
}
@@ -113,20 +100,16 @@ public class LeaderboardsMenu : MonoBehaviour
request.SetRequestHeader("ClientVersion", Application.version);
request.SetRequestHeader("ClientPlatform", Application.platform.ToString());
await request.SendWebRequest();
if (request.downloadHandler.text == null)
{
if (request.downloadHandler.text == null) {
UpdateStatus(true, "Failed to fetch leaderboard stats");
return;
}
UpdateStatus(false);
var jsonResponse = JObject.Parse(request.downloadHandler.text);
if ((bool)jsonResponse["success"])
{
if (mode != LeaderboardMode.Level && mode != LeaderboardMode.TotalXP)
{
if ((bool)jsonResponse["success"]) {
if (mode != LeaderboardMode.Level && mode != LeaderboardMode.TotalXP) {
var entries = jsonResponse["data"].ToObject<LeaderboardEntry[]>();
for (int i = 0; i < entries.Length; i++)
{
for (int i = 0; i < entries.Length; i++) {
var entry = entries[i];
var entryInfo = Instantiate(sampleObject, content.transform);
var usernameText = entryInfo.transform.GetChild(0).GetComponent<TMP_Text>();
@@ -138,14 +121,12 @@ public class LeaderboardsMenu : MonoBehaviour
usernameText.text = $"{entry.Username} (#{i + 1})";
scoreText.text = (mode == LeaderboardMode.Berry || mode == LeaderboardMode.TotalBerries ? "Berries: " : mode == LeaderboardMode.Coin ? "Coins: " : "Score: ") + Tools.FormatWithCommas(entry.Value);
if (BazookaManager.Instance.GetAccountID() == entry.UserID)
{
if (BazookaManager.Instance.GetAccountID() == entry.UserID) {
usernameText.text = $"<color=#7FFFD4>{usernameText.text}</color>";
scoreText.text = $"<color=#7FFFD4>{scoreText.text}</color>";
}
if (entry.CustomIcon == null)
{
if (entry.CustomIcon == null) {
playerIcon.sprite = Resources.Load<Sprite>("Icons/Icons/bird_" + entry.Icon);
if (entry.Icon == 1) playerIcon.sprite = Tools.GetIconForUser(entry.UserID);
playerOverlay.sprite = Resources.Load<Sprite>("Icons/Overlays/overlay_" + entry.Overlay);
@@ -153,33 +134,26 @@ public class LeaderboardsMenu : MonoBehaviour
if (entry.Overlay == 8) playerOverlay.transform.localPosition = new Vector2(-16.56f, 14.81f);
else if (entry.Overlay == 11) playerOverlay.transform.localPosition = new Vector2(-14.74451f, 20.39122f);
else if (entry.Overlay == 13) playerOverlay.transform.localPosition = new Vector2(-16.54019f, 14.70365f);
try
{
try {
playerIcon.color = new Color(entry.BirdColor[0] / 255f, entry.BirdColor[1] / 255f, entry.BirdColor[2] / 255f);
playerOverlay.color = new Color(entry.BirdColor[0] / 255f, entry.BirdColor[1] / 255f, entry.BirdColor[2] / 255f);
}
catch
{
catch {
playerIcon.color = Color.white;
playerOverlay.color = Color.white;
}
}
else playerIcon.gameObject.AddComponent<WaitingForCustomIcon>().ID = entry.CustomIcon;
playerIconButton.onClick.AddListener(async () =>
{
} else playerIcon.gameObject.AddComponent<WaitingForCustomIcon>().ID = entry.CustomIcon;
playerIconButton.onClick.AddListener(async () => {
var clone = Instantiate(profilePrefab.gameObject, profilePrefab.gameObject.transform.parent);
clone.SetActive(true);
await clone.GetComponent<ProfileMenu>().Init(entry.UserID);
});
entryInfo.SetActive(true);
}
}
else
{
} else {
var entries = jsonResponse["data"]
.ToObject<Account[]>()
.Select(entry =>
{
.Select(entry => {
var xp = Tools.CalculateXP(
entry.Stats.TotalNormalBerries,
entry.Stats.TotalPoisonBerries,
@@ -192,16 +166,14 @@ public class LeaderboardsMenu : MonoBehaviour
entry.Stats.TotalGoldenBerries
);
return new
{
return new {
Account = entry,
XP = xp
};
})
.OrderByDescending(x => x.XP)
.ToList();
for (int i = 0; i < entries.Count; i++)
{
for (int i = 0; i < entries.Count; i++) {
var entry = entries[i].Account;
var xp = entries[i].XP;
var entryInfo = Instantiate(sampleObject, content.transform);
@@ -214,14 +186,12 @@ public class LeaderboardsMenu : MonoBehaviour
usernameText.text = $"{entry.Username} (#{i + 1})";
scoreText.text = (mode == LeaderboardMode.Level ? "Level: " : "XP: ") + Tools.FormatWithCommas(mode == LeaderboardMode.Level ? Tools.GetLevelInfo(xp).level.ToString() : xp.ToString());
if (BazookaManager.Instance.GetAccountID() == entry.UserID)
{
if (BazookaManager.Instance.GetAccountID() == entry.UserID) {
usernameText.text = $"<color=#7FFFD4>{usernameText.text}</color>";
scoreText.text = $"<color=#7FFFD4>{scoreText.text}</color>";
}
if (entry.CustomIcon == null)
{
if (entry.CustomIcon == null) {
playerIcon.sprite = Resources.Load<Sprite>("Icons/Icons/bird_" + entry.Icon);
if (entry.Icon == 1) playerIcon.sprite = Tools.GetIconForUser(entry.UserID);
playerOverlay.sprite = Resources.Load<Sprite>("Icons/Overlays/overlay_" + entry.Overlay);
@@ -229,20 +199,16 @@ public class LeaderboardsMenu : MonoBehaviour
if (entry.Overlay == 8) playerOverlay.transform.localPosition = new Vector2(-16.56f, 14.81f);
else if (entry.Overlay == 11) playerOverlay.transform.localPosition = new Vector2(-14.74451f, 20.39122f);
else if (entry.Overlay == 13) playerOverlay.transform.localPosition = new Vector2(-16.54019f, 14.70365f);
try
{
try {
playerIcon.color = new Color(entry.BirdColor[0] / 255f, entry.BirdColor[1] / 255f, entry.BirdColor[2] / 255f);
playerOverlay.color = new Color(entry.BirdColor[0] / 255f, entry.BirdColor[1] / 255f, entry.BirdColor[2] / 255f);
}
catch
{
catch {
playerIcon.color = Color.white;
playerOverlay.color = Color.white;
}
}
else playerIcon.gameObject.AddComponent<WaitingForCustomIcon>().ID = entry.CustomIcon;
playerIconButton.onClick.AddListener(async () =>
{
} else playerIcon.gameObject.AddComponent<WaitingForCustomIcon>().ID = entry.CustomIcon;
playerIconButton.onClick.AddListener(async () => {
var clone = Instantiate(profilePrefab.gameObject, profilePrefab.gameObject.transform.parent);
clone.SetActive(true);
await clone.GetComponent<ProfileMenu>().Init(entry.UserID);
@@ -251,25 +217,20 @@ public class LeaderboardsMenu : MonoBehaviour
}
}
CustomIconLoader.Init(FindObjectsByType<WaitingForCustomIcon>(FindObjectsSortMode.None));
}
else
{
} else {
UpdateStatus(true, (string)jsonResponse["message"]);
}
backButton.interactable = true;
refreshButton.interactable = true;
}
private void UpdateStatus(bool enabled, string message = "")
{
private void UpdateStatus(bool enabled, string message = "") {
statusText.gameObject.SetActive(enabled);
statusText.text = message;
}
async void Update()
{
if (Keyboard.current.escapeKey.wasPressedThisFrame && FindFirstObjectByType<ProfileMenu>() == null)
{
async void Update() {
if (Keyboard.current.escapeKey.wasPressedThisFrame && FindFirstObjectByType<ProfileMenu>() == null) {
if (!selectionPanel.activeSelf) SwitchMenu(0);
else await SceneManager.LoadSceneAsync("MainMenu");
}
+11 -27
View File
@@ -4,23 +4,18 @@ using UnityEngine.Networking;
using UnityEngine.SceneManagement;
using UnityEngine.UI;
public class LoadingMenu : MonoBehaviour
{
public class LoadingMenu : MonoBehaviour {
[SerializeField] private TMP_Text text;
[SerializeField] private Button updateButton;
[SerializeField] private Button continueButton;
void Start()
{
if (!Application.isMobilePlatform)
{
void Start() {
if (!Application.isMobilePlatform) {
var width = Display.main.systemWidth;
var height = Display.main.systemHeight;
Screen.SetResolution(width, height, BazookaManager.Instance.GetSettingFullScreen());
QualitySettings.vSyncCount = BazookaManager.Instance.GetSettingVsync() ? 1 : -1;
}
else
{
} else {
Application.targetFrameRate = 360;
QualitySettings.vSyncCount = 0;
}
@@ -28,25 +23,20 @@ public class LoadingMenu : MonoBehaviour
CheckUpdate();
}
async void CheckUpdate()
{
async void CheckUpdate() {
using UnityWebRequest request = UnityWebRequest.Get(Endpoints.CAN_LOAD_CLIENT_ENDPOINT);
request.SetRequestHeader("Requester", "BerryDashClient");
request.SetRequestHeader("ClientVersion", Application.version);
request.SetRequestHeader("ClientPlatform", Application.platform.ToString());
await request.SendWebRequest();
if (request.downloadHandler.text == null)
{
if (request.downloadHandler.text == null) {
text.text = "Failed to check version";
return;
}
string response = request.downloadHandler.text;
if (response == "1")
{
if (response == "1") {
await SceneManager.LoadSceneAsync("MainMenu");
}
else if (response == "2")
{
} else if (response == "2") {
text.text = "Outdated client! You can still play the game and access the servers, but it isn't recommended.";
var updateButtonPos = updateButton.transform.localPosition;
@@ -55,9 +45,7 @@ public class LoadingMenu : MonoBehaviour
updateButton.gameObject.SetActive(true);
continueButton.gameObject.SetActive(true);
}
else if (response == "3")
{
} else if (response == "3") {
text.text = "Outdated client! You can still load into the game, but online features may not be available.";
var updateButtonPos = updateButton.transform.localPosition;
@@ -66,15 +54,11 @@ public class LoadingMenu : MonoBehaviour
updateButton.gameObject.SetActive(true);
continueButton.gameObject.SetActive(true);
}
else if (response == "4")
{
} else if (response == "4") {
text.text = "You are on a beta version of the game. You can still play the game and access the servers, but it is recommended to use the latest stable version.";
continueButton.transform.position = updateButton.transform.position;
continueButton.gameObject.SetActive(true);
}
else
{
} else {
text.text = "Outdated client! Please update your client to play";
updateButton.gameObject.SetActive(true);
}
+11 -23
View File
@@ -3,8 +3,7 @@ using UnityEngine;
using UnityEngine.InputSystem;
using UnityEngine.UI;
public class MenuScript : MonoBehaviour
{
public class MenuScript : MonoBehaviour {
[SerializeField] private Button closeButton;
[SerializeField] private TMP_Text updateText;
[SerializeField] private Button updateButton;
@@ -18,25 +17,19 @@ public class MenuScript : MonoBehaviour
[SerializeField] private Button iconMarketplaceButton;
[SerializeField] private TMP_Text iconMarketplaceButtonText;
void Awake()
{
if (PresistentData.latestVersion != null)
{
if (PresistentData.latestVersion != "-1")
{
void Awake() {
if (PresistentData.latestVersion != null) {
if (PresistentData.latestVersion != "-1") {
updateText.text = "Latest: v" + PresistentData.latestVersion ?? "N/A";
updateButton.gameObject.SetActive(PresistentData.latestVersion != Application.version);
}
else
{
} else {
updateText.text = "Latest: Loading...";
}
}
if (PresistentData.randomSplashes != null) splashText.text = PresistentData.randomSplashes[Random.Range(0, PresistentData.randomSplashes.Length)];
copyrightText.text = $"\\u00A9 {System.DateTime.Now.Year} Lncvrt. All rights reserved.";
if (!Application.isMobilePlatform && !Application.isEditor)
{
if (!Application.isMobilePlatform && !Application.isEditor) {
closeButton.gameObject.SetActive(true);
closeButton.onClick.AddListener(() => closePopup.SetActive(true));
}
@@ -45,13 +38,10 @@ public class MenuScript : MonoBehaviour
closePopupCloseButton.onClick.AddListener(() => Application.Quit());
}
void Start()
{
if (BazookaManager.Instance.GetAccountID() != null)
{
void Start() {
if (BazookaManager.Instance.GetAccountID() != null) {
profileButton.transform.GetChild(0).GetComponent<TMP_Text>().text = BazookaManager.Instance.GetAccountName();
profileButton.onClick.AddListener(async () =>
{
profileButton.onClick.AddListener(async () => {
var clone = Instantiate(profilePrefab.gameObject, profilePrefab.gameObject.transform.parent);
clone.SetActive(true);
await clone.GetComponent<ProfileMenu>().Init();
@@ -59,15 +49,13 @@ public class MenuScript : MonoBehaviour
profileButton.gameObject.SetActive(true);
}
if (Tools.GetLevelInfo().level < 3)
{
if (Tools.GetLevelInfo().level < 3) {
iconMarketplaceButton.interactable = false;
iconMarketplaceButtonText.text += "\n<size=12>You need level 3 or higher to access this</size>";
}
}
void Update()
{
void Update() {
if (Keyboard.current.escapeKey.wasPressedThisFrame && !GameObject.Find("ProfilePrefab(Clone)")) closePopup.SetActive(!closePopup.activeSelf);
}
}
+7 -15
View File
@@ -1,33 +1,25 @@
using UnityEngine;
using UnityEngine.SceneManagement;
public class MenuMusic : MonoBehaviour
{
public class MenuMusic : MonoBehaviour {
public static MenuMusic Instance;
void Awake()
{
if (Instance == null)
{
void Awake() {
if (Instance == null) {
Instance = this;
DontDestroyOnLoad(gameObject);
SceneManager.sceneLoaded += OnSceneLoaded;
}
else
{
} else {
Destroy(gameObject);
}
}
void Start()
{
void Start() {
GetComponent<AudioSource>().volume = BazookaManager.Instance.GetSettingMusicVolume();
}
void OnSceneLoaded(Scene scene, LoadSceneMode mode)
{
if (scene.name == "GamePlayer" || scene.name == "CustomGamePlayer")
{
void OnSceneLoaded(Scene scene, LoadSceneMode mode) {
if (scene.name == "GamePlayer" || scene.name == "CustomGamePlayer") {
SceneManager.sceneLoaded -= OnSceneLoaded;
Destroy(gameObject);
}
+5 -10
View File
@@ -4,20 +4,16 @@ using System.Security.Cryptography;
using System.Text;
using UnityEngine;
public class OldSavefileEncryption
{
public class OldSavefileEncryption {
public const string BAZOOKA_MANAGER_KEY = "5de0d5798d4eb751e13b668c1fc5297d";
public const string BAZOOKA_MANAGER_FILE_KEY = "e74af7ba21b8b4edd0e3f1d572d63c67";
public static string DecryptRaw(byte[] data)
{
if (BAZOOKA_MANAGER_KEY.Trim() == string.Empty)
{
public static string DecryptRaw(byte[] data) {
if (BAZOOKA_MANAGER_KEY.Trim() == string.Empty) {
Debug.LogError("Failed to decrypt: Encryption/Decryption keys not present");
return null;
}
try
{
try {
using Aes aes = Aes.Create();
aes.Key = Encoding.UTF8.GetBytes(BAZOOKA_MANAGER_KEY);
aes.Mode = CipherMode.CBC;
@@ -33,8 +29,7 @@ public class OldSavefileEncryption
return reader.ReadToEnd();
}
catch
{
catch {
return null;
}
}
+1 -2
View File
@@ -1,5 +1,4 @@
public class Endpoints
{
public class Endpoints {
private const string HOST = "games.lncvrt.xyz";
public const string BASE_URL = "https://" + HOST + "/api";
public const string BERRYDASH_ENDPOINT = BASE_URL + "/berrydash";
+33 -68
View File
@@ -5,8 +5,7 @@ using UnityEngine.InputSystem;
using UnityEngine.SceneManagement;
using UnityEngine.UI;
public class PlayMenu : MonoBehaviour
{
public class PlayMenu : MonoBehaviour {
[SerializeField] private GameObject selectionMenu;
[SerializeField] private GameObject customMenu;
[SerializeField] private Button customButton;
@@ -36,17 +35,14 @@ public class PlayMenu : MonoBehaviour
private readonly float defaultGoldenBerryChance = 5f;
private readonly float defaultNothingBerryChance = 0f;
void Awake()
{
customButton.onClick.AddListener(() =>
{
void Awake() {
customButton.onClick.AddListener(() => {
selectionMenu.SetActive(false);
customMenu.SetActive(true);
if (DiscordRPCHandler.Instance != null)
DiscordRPCHandler.Instance.UpdateRPC("Customizing to play the custom mode", "");
});
customBackButton.onClick.AddListener(() =>
{
customBackButton.onClick.AddListener(() => {
customMenu.SetActive(false);
selectionMenu.SetActive(true);
@@ -63,8 +59,7 @@ public class PlayMenu : MonoBehaviour
if (DiscordRPCHandler.Instance != null)
DiscordRPCHandler.Instance.UpdateRPC("Picking what mode they want to play", "");
});
customNormalizeButton.onClick.AddListener(() =>
{
customNormalizeButton.onClick.AddListener(() => {
float normalBerry = GetValueFrom(normalBerryChance);
float poisonBerry = GetValueFrom(poisonBerryChance);
float slowBerry = GetValueFrom(slowBerryChance);
@@ -124,56 +119,46 @@ public class PlayMenu : MonoBehaviour
float difference2 = addedChances2 - 100f;
bool fixedValues = false;
if (normalBerry > 0)
{
if (normalBerry > 0) {
NormalizeTwo(normalBerryChance, fixedValues, normalBerry, difference2);
fixedValues = true;
}
if (poisonBerry > 0)
{
if (poisonBerry > 0) {
NormalizeTwo(poisonBerryChance, fixedValues, poisonBerry, difference2);
fixedValues = true;
}
if (slowBerry > 0)
{
if (slowBerry > 0) {
NormalizeTwo(slowBerryChance, fixedValues, slowBerry, difference2);
fixedValues = true;
}
if (ultraBerry > 0)
{
if (ultraBerry > 0) {
NormalizeTwo(ultraBerryChance, fixedValues, ultraBerry, difference2);
fixedValues = true;
}
if (speedyBerry > 0)
{
if (speedyBerry > 0) {
NormalizeTwo(speedyBerryChance, fixedValues, speedyBerry, difference2);
fixedValues = true;
}
if (randomBerry > 0)
{
if (randomBerry > 0) {
NormalizeTwo(randomBerryChance, fixedValues, randomBerry, difference2);
fixedValues = true;
}
if (antiBerry > 0)
{
if (antiBerry > 0) {
NormalizeTwo(antiBerryChance, fixedValues, antiBerry, difference2);
fixedValues = true;
}
if (goldenBerry > 0)
{
if (goldenBerry > 0) {
NormalizeTwo(goldenBerryChance, fixedValues, goldenBerry, difference2);
fixedValues = true;
}
if (nothingBerry > 0)
{
if (nothingBerry > 0) {
NormalizeTwo(nothingBerryChance, fixedValues, nothingBerry, difference2);
fixedValues = true;
}
ValidateTotal();
});
customPlayButton.onClick.AddListener(async () =>
{
customPlayButton.onClick.AddListener(async () => {
GameObject obj = new("CustomGameTempData");
obj.AddComponent<CustomGameTempData>();
CustomGameTempData customGameTempData = obj.GetComponent<CustomGameTempData>();
@@ -209,20 +194,17 @@ public class PlayMenu : MonoBehaviour
nothingBerryChance.onDeselect.AddListener((value) => OnDeselect(value, nothingBerryChance));
}
void Start()
{
void Start() {
if (DiscordRPCHandler.Instance != null)
DiscordRPCHandler.Instance.UpdateRPC("Picking what mode they want to play", "");
if (Tools.GetLevelInfo().level < 5)
{
if (Tools.GetLevelInfo().level < 5) {
customButton.interactable = false;
customButton.transform.GetChild(0).GetComponent<TMP_Text>().text += "\n<size=12>You need level 5 or higher to access this</size>";
}
}
void ValidateTotal()
{
void ValidateTotal() {
customBackButton.interactable = false;
customPlayButton.interactable = false;
customNormalizeButton.interactable = false;
@@ -236,39 +218,31 @@ public class PlayMenu : MonoBehaviour
total += GetValueFrom(antiBerryChance);
total += GetValueFrom(goldenBerryChance);
total += GetValueFrom(nothingBerryChance);
if (total == 100f)
{
if (total == 100f) {
customBackButton.interactable = true;
customPlayButton.interactable = true;
validateTotalText.gameObject.SetActive(false);
}
else
{
} else {
customNormalizeButton.interactable = true;
validateTotalText.text = "Total must add up to 100%!";
validateTotalText.gameObject.SetActive(true);
}
}
private float GetValueFrom(TMP_InputField inputField)
{
private float GetValueFrom(TMP_InputField inputField) {
return GetValueFroText(inputField.text);
}
private float GetValueFroText(string text)
{
try
{
private float GetValueFroText(string text) {
try {
return float.Parse(text.Replace("%", "").Trim());
}
catch
{
catch {
return 0f;
}
}
void OnSelect(string value, TMP_InputField inputField)
{
void OnSelect(string value, TMP_InputField inputField) {
validateTotalText.gameObject.SetActive(false);
customBackButton.interactable = false;
customPlayButton.interactable = false;
@@ -277,40 +251,31 @@ public class PlayMenu : MonoBehaviour
inputField.stringPosition = inputField.text.Length;
}
void OnDeselect(string value, TMP_InputField inputField)
{
if (float.TryParse(value, out var value2) && value2 < 0f)
{
void OnDeselect(string value, TMP_InputField inputField) {
if (float.TryParse(value, out var value2) && value2 < 0f) {
value = "0";
}
inputField.text = value + "%";
ValidateTotal();
}
void NormalizeOne(TMP_InputField inputField, float berryChance, int divideBy, float difference)
{
void NormalizeOne(TMP_InputField inputField, float berryChance, int divideBy, float difference) {
inputField.text = (berryChance - (difference / divideBy)).ToString() + "%";
inputField.stringPosition = inputField.text.Length;
}
void NormalizeTwo(TMP_InputField inputField, bool fixedValues, float berryChance, float difference2)
{
if (!fixedValues)
{
void NormalizeTwo(TMP_InputField inputField, bool fixedValues, float berryChance, float difference2) {
if (!fixedValues) {
inputField.text = (berryChance - difference2).ToString() + "%";
inputField.stringPosition = inputField.text.Length;
}
else
{
} else {
inputField.text = berryChance.ToString() + "%";
inputField.stringPosition = inputField.text.Length;
}
}
async void Update()
{
if (Keyboard.current.escapeKey.wasPressedThisFrame && customBackButton.interactable)
{
async void Update() {
if (Keyboard.current.escapeKey.wasPressedThisFrame && customBackButton.interactable) {
if (customMenu.activeSelf) customBackButton.onClick.Invoke();
else await SceneManager.LoadSceneAsync("MainMenu");
}
+8 -16
View File
@@ -4,33 +4,28 @@ using UnityEngine;
using UnityEngine.Networking;
using UnityEngine.SceneManagement;
public class PresistentData : MonoBehaviour
{
public class PresistentData : MonoBehaviour {
public static PresistentData Instance;
private bool loadingDone = false;
public static string latestVersion = null;
public static string[] randomSplashes = null;
private async void Awake()
{
if (Instance != null && Instance != this)
{
private async void Awake() {
if (Instance != null && Instance != this) {
Destroy(gameObject);
return;
}
Instance = this;
DontDestroyOnLoad(gameObject);
if (!loadingDone)
{
if (!loadingDone) {
loadingDone = true;
await GetLatestVersion();
await GetRandomSplashes();
}
}
private async static Task GetLatestVersion()
{
private async static Task GetLatestVersion() {
using UnityWebRequest request = UnityWebRequest.Get(Endpoints.LATEST_VERSION_ENDPOINT);
request.SetRequestHeader("Requester", "BerryDashClient");
request.SetRequestHeader("ClientVersion", Application.version);
@@ -41,15 +36,13 @@ public class PresistentData : MonoBehaviour
SceneManager.GetActiveScene().name == "MainMenu" &&
latestVersion != "-1" &&
GameObject.Find("Canvas/LatestVersionText").TryGetComponent<TextMeshProUGUI>(out var text)
)
{
) {
text.text = "Latest: v" + latestVersion ?? "N/A";
text.transform.GetChild(0).gameObject.SetActive(latestVersion != Application.version);
}
}
private async static Task GetRandomSplashes()
{
private async static Task GetRandomSplashes() {
using UnityWebRequest request = UnityWebRequest.Get(Endpoints.RANDOM_SPLASHES_ENDPOINT);
request.SetRequestHeader("Requester", "BerryDashClient");
request.SetRequestHeader("ClientVersion", Application.version);
@@ -60,8 +53,7 @@ public class PresistentData : MonoBehaviour
SceneManager.GetActiveScene().name == "MainMenu" &&
randomSplashes != null &&
GameObject.Find("Canvas/SplashText").TryGetComponent<TextMeshProUGUI>(out var text)
)
{
) {
text.text = randomSplashes[Random.Range(0, randomSplashes.Length)];
}
}
+37 -76
View File
@@ -9,8 +9,7 @@ using UnityEngine.InputSystem;
using UnityEngine.Networking;
using UnityEngine.UI;
public class ProfileMenu : MonoBehaviour
{
public class ProfileMenu : MonoBehaviour {
[SerializeField] private Button exitButton;
[SerializeField] private Button refreshButton;
[SerializeField] private Button postButton;
@@ -41,8 +40,7 @@ public class ProfileMenu : MonoBehaviour
private GameObject popupObject;
void Awake()
{
void Awake() {
exitButton.onClick.AddListener(() => Destroy(gameObject));
}
@@ -64,8 +62,7 @@ public class ProfileMenu : MonoBehaviour
Color playerIconColor,
Color playerOverlayColor,
string customIcon
)
{
) {
var xp = Tools.CalculateXP(BigInteger.Parse(normalBerries), BigInteger.Parse(poisonBerries), BigInteger.Parse(slowBerries), BigInteger.Parse(ultraBerries), BigInteger.Parse(speedyBerries), BigInteger.Parse(coinBerries), BigInteger.Parse(randomBerries), BigInteger.Parse(antiBerries), BigInteger.Parse(goldenBerries));
var level = Tools.GetLevelInfo(xp).level;
@@ -82,8 +79,7 @@ public class ProfileMenu : MonoBehaviour
playerLevelAndXPStat.text = $"Level: {Tools.FormatWithCommas((BigInteger)level)}\nXP: {Tools.FormatWithCommas(xp)}";
playerNameText.text = playerName;
if (customIcon == null)
{
if (customIcon == null) {
playerIconImage.sprite = Resources.Load<Sprite>("Icons/Icons/bird_" + playerIcon);
if (playerIcon == 1) playerIconImage.sprite = Tools.GetIconForUser(playerID);
playerOverlayImage.sprite = Resources.Load<Sprite>("Icons/Overlays/overlay_" + playerOverlay);
@@ -93,15 +89,12 @@ public class ProfileMenu : MonoBehaviour
else if (playerOverlay == 13) playerOverlayImage.transform.localPosition = new UnityEngine.Vector2(-16.54019f, 14.70365f);
playerIconImage.color = playerIconColor;
playerOverlayImage.color = playerOverlayColor;
}
else
{
} else {
var waitingForCustomIcon = playerIconImage.gameObject.AddComponent<WaitingForCustomIcon>();
waitingForCustomIcon.ID = customIcon;
CustomIconLoader.Init(new[] { waitingForCustomIcon });
}
if (BazookaManager.Instance.GetAccountID() == playerID)
{
if (BazookaManager.Instance.GetAccountID() == playerID) {
postButton.gameObject.SetActive(true);
postButton.onClick.AddListener(UploadPostPopup);
}
@@ -114,25 +107,21 @@ public class ProfileMenu : MonoBehaviour
await RefreshPosts(playerID, playerName);
}
public async Task Init(BigInteger playerID)
{
public async Task Init(BigInteger playerID) {
if (BazookaManager.Instance.GetAccountID() == playerID) { await Init(); return; }
using UnityWebRequest request = UnityWebRequest.Get(Endpoints.BD_ACCOUNT_ENDPOINT + "?id=" + playerID.ToString() + "&exact=true");
request.SetRequestHeader("Requester", "BerryDashClient");
request.SetRequestHeader("ClientVersion", Application.version);
request.SetRequestHeader("ClientPlatform", Application.platform.ToString());
await request.SendWebRequest();
if (request.downloadHandler.text == null)
{
if (request.downloadHandler.text == null) {
Destroy(gameObject);
return;
}
string response = request.downloadHandler.text;
try
{
try {
var jsonResponse = JObject.Parse(response);
if ((bool)jsonResponse["success"])
{
if ((bool)jsonResponse["success"]) {
var data = jsonResponse["data"].ToObject<Account>();
@@ -159,20 +148,16 @@ public class ProfileMenu : MonoBehaviour
overlayColor,
data.CustomIcon
);
}
else
{
} else {
Destroy(gameObject);
}
}
catch
{
catch {
Destroy(gameObject);
}
}
public async Task Init()
{
public async Task Init() {
var customIconData = BazookaManager.Instance.GetCustomBirdIconData();
var iconColor = customIconData.Selected == null ? BazookaManager.Instance.GetColorSettingIcon() : null;
var overlayColor = customIconData.Selected == null ? BazookaManager.Instance.GetColorSettingOverlay() : null;
@@ -197,15 +182,12 @@ public class ProfileMenu : MonoBehaviour
);
}
async Task RefreshPosts(BigInteger playerID, string playerName)
{
async Task RefreshPosts(BigInteger playerID, string playerName) {
exitButton.interactable = false;
refreshButton.interactable = false;
postButton.interactable = false;
foreach (Transform post in postSample.transform.parent)
{
if (post.gameObject.activeSelf)
{
foreach (Transform post in postSample.transform.parent) {
if (post.gameObject.activeSelf) {
Destroy(post.gameObject);
}
}
@@ -214,16 +196,14 @@ public class ProfileMenu : MonoBehaviour
request.SetRequestHeader("ClientVersion", Application.version);
request.SetRequestHeader("ClientPlatform", Application.platform.ToString());
await request.SendWebRequest();
if (request.downloadHandler.text == null)
{
if (request.downloadHandler.text == null) {
exitButton.interactable = true;
refreshButton.interactable = true;
return;
}
string response = request.downloadHandler.text;
var posts = JArray.Parse(response).ToObject<ProfileMessageResponse[]>();
foreach (var post in posts)
{
foreach (var post in posts) {
var entry = Instantiate(postSample, postSample.transform.parent);
var entryUsername = entry.transform.GetChild(0).GetComponent<TMP_Text>();
var entryLikesParent = entry.transform.GetChild(1);
@@ -238,10 +218,8 @@ public class ProfileMenu : MonoBehaviour
entryLikesTexture.text = post.Likes < 0 ? "\\uf165" : "\\uf164";
entryLikesTexture.color = post.Likes < 0 ? new Color(1f, 0f, 0.5f) : new Color(1f, 1f, 0f);
entryLikesCount.text = Tools.FormatWithCommas(post.Likes);
entryLikesButton.onClick.AddListener(() =>
{
if (canVote && BazookaManager.Instance.GetAccountID() != null && BazookaManager.Instance.GetAccountID() != playerID)
{
entryLikesButton.onClick.AddListener(() => {
if (canVote && BazookaManager.Instance.GetAccountID() != null && BazookaManager.Instance.GetAccountID() != playerID) {
var likedPosts = BazookaManager.Instance
.GetLikedPosts()
.Select(x => x.ToString())
@@ -251,8 +229,7 @@ public class ProfileMenu : MonoBehaviour
});
entryMessage.text = post.Content;
entryTimestamp.text = post.Timestamp.ToString();
if (BazookaManager.Instance.GetAccountID() == playerID)
{
if (BazookaManager.Instance.GetAccountID() == playerID) {
entryDeleteButton.gameObject.SetActive(true);
entryDeleteButton.onClick.AddListener(async () => await DeletePost(entry, post.ID));
}
@@ -267,8 +244,7 @@ public class ProfileMenu : MonoBehaviour
postButton.interactable = true;
}
void VotePost(BigInteger postId, TMP_Text entryLikesCount, TMP_Text entryLikesTexture)
{
void VotePost(BigInteger postId, TMP_Text entryLikesCount, TMP_Text entryLikesTexture) {
var popup = Instantiate(voteOverlay, voteOverlay.transform.parent);
popupObject = popup;
popup.SetActive(true);
@@ -276,16 +252,14 @@ public class ProfileMenu : MonoBehaviour
var likeButton = popup.transform.GetChild(0).GetChild(2).GetComponent<Button>();
var dislikeButton = popup.transform.GetChild(0).GetChild(3).GetComponent<Button>();
exitButton.onClick.AddListener(() => Destroy(popup));
likeButton.onClick.AddListener(async () =>
{
likeButton.onClick.AddListener(async () => {
canVote = false;
popupObject = null;
Destroy(popup);
await SendPostVote(postId, true, entryLikesCount, entryLikesTexture);
canVote = true;
});
dislikeButton.onClick.AddListener(async () =>
{
dislikeButton.onClick.AddListener(async () => {
canVote = false;
popupObject = null;
Destroy(popup);
@@ -294,8 +268,7 @@ public class ProfileMenu : MonoBehaviour
});
}
async Task SendPostVote(BigInteger postId, bool liked, TMP_Text entryLikesCount, TMP_Text entryLikesTexture)
{
async Task SendPostVote(BigInteger postId, bool liked, TMP_Text entryLikesCount, TMP_Text entryLikesTexture) {
using UnityWebRequest request = UnityWebRequest.Put(Endpoints.PROFILE_POSTS_ENDPOINT + $"?id={postId}&liked={liked}", new WWWForm().data);
request.SetRequestHeader("Authorization", BazookaManager.Instance.GetAccountSession());
request.SetRequestHeader("Requester", "BerryDashClient");
@@ -304,8 +277,7 @@ public class ProfileMenu : MonoBehaviour
await request.SendWebRequest();
if (request.downloadHandler.text == null) return;
var jsonResponse = JObject.Parse(request.downloadHandler.text);
if ((bool)jsonResponse["success"])
{
if ((bool)jsonResponse["success"]) {
BigInteger likes = BigInteger.Parse((string)jsonResponse["data"]["likes"]);
entryLikesCount.text = Tools.FormatWithCommas(likes);
entryLikesTexture.text = likes < 0 ? "\\uf165" : "\\uf164";
@@ -316,8 +288,7 @@ public class ProfileMenu : MonoBehaviour
}
}
void UploadPostPopup()
{
void UploadPostPopup() {
var popup = Instantiate(postOverlay, postOverlay.transform.parent);
popupObject = popup;
popup.SetActive(true);
@@ -325,13 +296,11 @@ public class ProfileMenu : MonoBehaviour
inputBox.onSelect.AddListener((_) => inputBox.caretPosition = inputBox.text.Length);
var cancelButton = popup.transform.GetChild(0).GetChild(2).GetComponent<Button>();
var submitButton = popup.transform.GetChild(0).GetChild(3).GetComponent<Button>();
cancelButton.onClick.AddListener(() =>
{
cancelButton.onClick.AddListener(() => {
Destroy(popup);
popupObject = null;
});
submitButton.onClick.AddListener(async () =>
{
submitButton.onClick.AddListener(async () => {
if (inputBox.text.Trim().Length == 0) return;
popupObject = null;
Destroy(popup);
@@ -339,8 +308,7 @@ public class ProfileMenu : MonoBehaviour
});
}
async Task UploadPost(string message)
{
async Task UploadPost(string message) {
WWWForm dataForm = new();
dataForm.AddField("content", message);
using UnityWebRequest request = UnityWebRequest.Post(Endpoints.PROFILE_POSTS_ENDPOINT, dataForm);
@@ -349,36 +317,29 @@ public class ProfileMenu : MonoBehaviour
request.SetRequestHeader("ClientVersion", Application.version);
request.SetRequestHeader("ClientPlatform", Application.platform.ToString());
await request.SendWebRequest();
if (request.result == UnityWebRequest.Result.Success && request.responseCode == 200)
{
if (request.result == UnityWebRequest.Result.Success && request.responseCode == 200) {
await RefreshPosts(BazookaManager.Instance.GetAccountID() ?? 0, BazookaManager.Instance.GetAccountName());
}
}
async Task DeletePost(GameObject entryObject, BigInteger targetId)
{
async Task DeletePost(GameObject entryObject, BigInteger targetId) {
using UnityWebRequest request = UnityWebRequest.Delete(Endpoints.PROFILE_POSTS_ENDPOINT + "?id=" + targetId.ToString());
request.SetRequestHeader("Authorization", BazookaManager.Instance.GetAccountSession());
request.SetRequestHeader("Requester", "BerryDashClient");
request.SetRequestHeader("ClientVersion", Application.version);
request.SetRequestHeader("ClientPlatform", Application.platform.ToString());
await request.SendWebRequest();
if (request.result == UnityWebRequest.Result.Success && request.responseCode == 200)
{
if (request.result == UnityWebRequest.Result.Success && request.responseCode == 200) {
Destroy(entryObject);
}
}
void Update()
{
if (Keyboard.current.escapeKey.wasPressedThisFrame)
{
if (popupObject != null)
{
void Update() {
if (Keyboard.current.escapeKey.wasPressedThisFrame) {
if (popupObject != null) {
if (!canVote) canVote = true;
Destroy(popupObject);
}
else Destroy(gameObject);
} else Destroy(gameObject);
}
}
}
+3 -6
View File
@@ -1,18 +1,15 @@
using UnityEngine;
using UnityEngine.UI;
public class RainbowImage : MonoBehaviour
{
public class RainbowImage : MonoBehaviour {
[SerializeField] private float frequency = 1f;
private Image targetImage;
void Awake()
{
void Awake() {
targetImage = gameObject.GetComponent<Image>();
}
void Update()
{
void Update() {
float t = Time.time * frequency;
float r = Mathf.Sin(t) * 0.5f + 0.5f;
float g = Mathf.Sin(t + 2f) * 0.5f + 0.5f;
+3 -6
View File
@@ -1,17 +1,14 @@
using UnityEngine;
public class RainbowSpriteRender : MonoBehaviour
{
public class RainbowSpriteRender : MonoBehaviour {
public float frequency = 1f;
private SpriteRenderer targetImage;
void Awake()
{
void Awake() {
targetImage = gameObject.GetComponent<SpriteRenderer>();
}
void Update()
{
void Update() {
float t = Time.time * frequency;
float r = Mathf.Sin(t) * 0.5f + 0.5f;
float g = Mathf.Sin(t + 2f) * 0.5f + 0.5f;
+3 -6
View File
@@ -1,18 +1,15 @@
using TMPro;
using UnityEngine;
public class RainbowText : MonoBehaviour
{
public class RainbowText : MonoBehaviour {
[SerializeField] private float frequency = 1f;
private TMP_Text targetImage;
void Awake()
{
void Awake() {
targetImage = gameObject.GetComponent<TMP_Text>();
}
void Update()
{
void Update() {
float t = Time.time * frequency;
float r = Mathf.Sin(t) * 0.5f + 0.5f;
float g = Mathf.Sin(t + 2f) * 0.5f + 0.5f;
+14 -29
View File
@@ -5,8 +5,7 @@ using UnityEngine.InputSystem;
using UnityEngine.SceneManagement;
using UnityEngine.UI;
public class SettingsMenu : MonoBehaviour
{
public class SettingsMenu : MonoBehaviour {
[SerializeField] private GameObject settingsMenu;
[SerializeField] private ColorPanel colorMenu;
[SerializeField] private Button toggleButton;
@@ -24,11 +23,9 @@ public class SettingsMenu : MonoBehaviour
[SerializeField] private int colorType = 0;
[SerializeField] private bool colorCanSave = true;
private void Start()
{
private void Start() {
colorMenu.Init(Color.white, Color.white);
colorMenu.OnColorChanged += color =>
{
colorMenu.OnColorChanged += color => {
if (!colorCanSave) return;
if (colorType == 0) BazookaManager.Instance.SetColorSettingBackground(color);
@@ -39,8 +36,7 @@ public class SettingsMenu : MonoBehaviour
foreach (CustomColorObject customColorObject in FindObjectsByType<CustomColorObject>(FindObjectsSortMode.None)) customColorObject.SetColor();
};
toggleButton.onClick.AddListener(() =>
{
toggleButton.onClick.AddListener(() => {
settingsMenu.SetActive(!settingsMenu.activeSelf);
colorMenu.gameObject.SetActive(!colorMenu.gameObject.activeSelf);
toggleButton.transform.GetChild(0).GetComponent<TMP_Text>().text = settingsMenu.activeSelf ? "Colors" : "Settings";
@@ -51,42 +47,35 @@ public class SettingsMenu : MonoBehaviour
musicSlider.value = BazookaManager.Instance.GetSettingMusicVolume();
sfxSlider.value = BazookaManager.Instance.GetSettingSFXVolume();
if (!Application.isMobilePlatform)
{
if (!Application.isMobilePlatform) {
setting1toggle.isOn = BazookaManager.Instance.GetSettingFullScreen() == true;
setting2toggle.isOn = BazookaManager.Instance.GetSettingShowFPS() == true;
setting3toggle.isOn = BazookaManager.Instance.GetSettingVsync() == true;
setting4toggle.isOn = BazookaManager.Instance.GetSettingHideSocials() == true;
setting5toggle.isOn = BazookaManager.Instance.GetSettingRandomMusic() == true;
setting1toggle.onValueChanged.AddListener(value =>
{
setting1toggle.onValueChanged.AddListener(value => {
BazookaManager.Instance.SetSettingFullScreen(value);
var width = Display.main.systemWidth;
var height = Display.main.systemHeight;
Screen.SetResolution(width, height, value);
});
setting3toggle.onValueChanged.AddListener(value =>
{
setting3toggle.onValueChanged.AddListener(value => {
BazookaManager.Instance.SetSettingVsync(value);
QualitySettings.vSyncCount = value ? 1 : -1;
});
}
else
{
} else {
setting1toggle.gameObject.SetActive(false);
setting2toggle.isOn = BazookaManager.Instance.GetSettingShowFPS() == true;
setting3toggle.gameObject.SetActive(false);
setting4toggle.isOn = BazookaManager.Instance.GetSettingHideSocials() == true;
setting5toggle.isOn = BazookaManager.Instance.GetSettingRandomMusic() == true;
}
setting2toggle.onValueChanged.AddListener(value =>
{
setting2toggle.onValueChanged.AddListener(value => {
BazookaManager.Instance.SetSettingShowFPS(value);
});
setting4toggle.onValueChanged.AddListener(value => BazookaManager.Instance.SetSettingHideSocials(value));
setting5toggle.onValueChanged.AddListener(value => BazookaManager.Instance.SetSettingRandomMusic(value));
musicSlider.onValueChanged.AddListener(value =>
{
musicSlider.onValueChanged.AddListener(value => {
BazookaManager.Instance.SetSettingMusicVolume(value);
MenuMusic.Instance.GetComponent<AudioSource>().volume = value;
});
@@ -94,13 +83,11 @@ public class SettingsMenu : MonoBehaviour
Tools.RefreshHierarchy(setting1toggle.transform.parent.gameObject);
}
void SwitchColorType(int color = -1)
{
void SwitchColorType(int color = -1) {
var type = color == -1 ? colorType : color;
var text = colorMenu.transform.GetChild(0).GetComponent<TMP_Text>();
var colorToSet = new JArray(255, 255, 255);
switch (type)
{
switch (type) {
case 0: //IGBGColor
text.text = "Menu background color";
colorType = 1;
@@ -137,10 +124,8 @@ public class SettingsMenu : MonoBehaviour
colorCanSave = true;
}
async void Update()
{
if (Keyboard.current.escapeKey.wasPressedThisFrame)
{
async void Update() {
if (Keyboard.current.escapeKey.wasPressedThisFrame) {
if (colorMenu.gameObject.activeSelf) toggleButton.onClick.Invoke();
else await SceneManager.LoadSceneAsync("MainMenu");
}
+8 -17
View File
@@ -5,8 +5,7 @@ using UnityEngine.InputSystem;
using UnityEngine.SceneManagement;
using UnityEngine.UI;
public class StatsMenu : MonoBehaviour
{
public class StatsMenu : MonoBehaviour {
[SerializeField] private GameObject panel;
[SerializeField] private TMP_Text normalBerryStat;
@@ -29,8 +28,7 @@ public class StatsMenu : MonoBehaviour
[SerializeField] private RectTransform progressFilledRect;
void Start()
{
void Start() {
normalBerryStat.text = Tools.FormatWithCommas(BazookaManager.Instance.GetGameStoreTotalNormalBerries());
poisonBerryStat.text = Tools.FormatWithCommas(BazookaManager.Instance.GetGameStoreTotalPoisonBerries());
slowBerryStat.text = Tools.FormatWithCommas(BazookaManager.Instance.GetGameStoreTotalSlowBerries());
@@ -43,8 +41,7 @@ public class StatsMenu : MonoBehaviour
coinStat.text = Tools.FormatWithCommas(BazookaManager.Instance.GetCustomBirdIconData().Balance);
var customIcon = BazookaManager.Instance.GetCustomBirdIconData().Selected;
if (customIcon == null)
{
if (customIcon == null) {
int icon = BazookaManager.Instance.GetBirdIcon();
int overlay = BazookaManager.Instance.GetBirdOverlay();
var iconColor = BazookaManager.Instance.GetColorSettingIcon();
@@ -56,8 +53,7 @@ public class StatsMenu : MonoBehaviour
if (overlay == 8) playerOverlay.rectTransform.localPosition = new Vector3(-27.6232f, 23.42824f, 0f);
else if (overlay == 11) playerOverlay.rectTransform.localPosition = new Vector3(-24.5611f, 32.250931f, 0f);
else if (overlay == 13) playerOverlay.rectTransform.localPosition = new Vector3(-27.56624f, 23.25544f, 0f);
try
{
try {
playerIcon.color = new Color(
int.Parse(iconColor[0].ToString()) / 255f,
int.Parse(iconColor[1].ToString()) / 255f,
@@ -69,14 +65,11 @@ public class StatsMenu : MonoBehaviour
int.Parse(overlayColor[2].ToString()) / 255f
);
}
catch
{
catch {
playerIcon.color = Color.white;
playerOverlay.color = Color.white;
}
}
else
{
} else {
var waitingForCustomIcon = playerIcon.gameObject.AddComponent<WaitingForCustomIcon>();
waitingForCustomIcon.ID = customIcon;
CustomIconLoader.Init(new[] { waitingForCustomIcon });
@@ -91,13 +84,11 @@ public class StatsMenu : MonoBehaviour
Tools.RefreshHierarchy(panel);
}
async void Update()
{
async void Update() {
if (Keyboard.current.escapeKey.wasPressedThisFrame) await SceneManager.LoadSceneAsync("MainMenu");
}
void SetXPProgressFilled(int progress)
{
void SetXPProgressFilled(int progress) {
int newProgress = Math.Clamp(progress, 0, 100);
progressFilledRect.sizeDelta = new Vector2(newProgress * 3, progressFilledRect.sizeDelta.y);
progressFilledRect.anchoredPosition = new Vector2((newProgress * 3 - 300f) * 0.5f, progressFilledRect.anchoredPosition.y);
+14 -27
View File
@@ -1,4 +1,4 @@
using System;
using System;
using System.Numerics;
using System.Security.Cryptography;
using System.Text;
@@ -6,10 +6,8 @@ using TMPro;
using UnityEngine;
using UnityEngine.UI;
public static class Tools
{
public static Sprite GetIconForUser(BigInteger user)
{
public static class Tools {
public static Sprite GetIconForUser(BigInteger user) {
if (user == 1) return Resources.Load<Sprite>("Icons/Icons/bird_-1");
else if (user == 2) return Resources.Load<Sprite>("Icons/Icons/bird_-2");
else if (user == 4) return Resources.Load<Sprite>("Icons/Icons/bird_-3");
@@ -17,25 +15,21 @@ public static class Tools
else return Resources.Load<Sprite>("Icons/Icons/bird_1");
}
public static string FormatWithCommas(string number)
{
public static string FormatWithCommas(string number) {
try { return FormatWithCommas(BigInteger.Parse(number)); }
catch { return number; }
}
public static string FormatWithCommas(BigInteger number)
{
public static string FormatWithCommas(BigInteger number) {
return string.Format("{0:N0}", number);
}
public static void UpdateStatusText(TMP_Text statusText, string message, Color color)
{
public static void UpdateStatusText(TMP_Text statusText, string message, Color color) {
statusText.text = message;
statusText.color = color;
}
public static Sprite GetSpriteFromBase64(string base64)
{
public static Sprite GetSpriteFromBase64(string base64) {
byte[] imageData = Convert.FromBase64String(base64);
Texture2D tex = new(2, 2, TextureFormat.ARGB32, false);
if (!tex.LoadImage(imageData)) return null;
@@ -46,14 +40,12 @@ public static class Tools
return Sprite.Create(tex, new Rect(0, 0, tex.width, tex.height), new UnityEngine.Vector2(0.5f, 0.5f));
}
public static void RefreshHierarchy(GameObject root)
{
public static void RefreshHierarchy(GameObject root) {
foreach (Transform child in root.transform) RefreshHierarchy(child.gameObject);
if (root.TryGetComponent<RectTransform>(out var rect)) LayoutRebuilder.ForceRebuildLayoutImmediate(rect);
}
public static string Sha512Sum(byte[] data)
{
public static string Sha512Sum(byte[] data) {
using var sha512 = SHA512.Create();
var hash = sha512.ComputeHash(data);
@@ -64,8 +56,7 @@ public static class Tools
return sb.ToString();
}
public static BigInteger CalculateXP(BigInteger normalBerries, BigInteger poisonBerries, BigInteger slowBerries, BigInteger ultraBerries, BigInteger speedyBerries, BigInteger coinBerries, BigInteger randomBerries, BigInteger antiBerries, BigInteger goldenBerries)
{
public static BigInteger CalculateXP(BigInteger normalBerries, BigInteger poisonBerries, BigInteger slowBerries, BigInteger ultraBerries, BigInteger speedyBerries, BigInteger coinBerries, BigInteger randomBerries, BigInteger antiBerries, BigInteger goldenBerries) {
BigInteger totalXp = 0;
totalXp += normalBerries;
totalXp -= poisonBerries;
@@ -80,8 +71,7 @@ public static class Tools
return totalXp;
}
public static BigInteger CalculateXP()
{
public static BigInteger CalculateXP() {
return CalculateXP(
BazookaManager.Instance.GetGameStoreTotalNormalBerries(),
BazookaManager.Instance.GetGameStoreTotalPoisonBerries(),
@@ -95,8 +85,7 @@ public static class Tools
);
}
public static (BigInteger totalXp, double level, BigInteger currentXpInLevel, BigInteger totalXpForLevel, double percentDone) GetLevelInfo(BigInteger xp)
{
public static (BigInteger totalXp, double level, BigInteger currentXpInLevel, BigInteger totalXpForLevel, double percentDone) GetLevelInfo(BigInteger xp) {
double levelDivisor = 50.0;
double discriminant = 95 * 95 + levelDivisor * 2 * (double)xp;
@@ -116,14 +105,12 @@ public static class Tools
return (xp, flooredLevel + 1, currentXpInLevel, totalXpForLevel, percentDone);
}
public static (BigInteger totalXp, double level, BigInteger currentXpInLevel, BigInteger totalXpForLevel, double percentDone) GetLevelInfo()
{
public static (BigInteger totalXp, double level, BigInteger currentXpInLevel, BigInteger totalXpForLevel, double percentDone) GetLevelInfo() {
var (totalXp, level, currentXpInLevel, totalXpForLevel, percentDone) = GetLevelInfo(CalculateXP());
return (totalXp, level, currentXpInLevel, totalXpForLevel, percentDone);
}
public static string FormatHumanTime(long unixTimestamp)
{
public static string FormatHumanTime(long unixTimestamp) {
DateTime date = DateTimeOffset.FromUnixTimeSeconds(unixTimestamp).LocalDateTime;
DateTime now = DateTime.Now;
+1 -2
View File
@@ -3,8 +3,7 @@ using Newtonsoft.Json;
using UnityEngine.Scripting;
[Preserve]
public class Account
{
public class Account {
[Preserve]
[JsonProperty("id")]
public BigInteger UserID { get; set; }
+1 -2
View File
@@ -3,8 +3,7 @@ using Newtonsoft.Json;
using UnityEngine.Scripting;
[Preserve]
public class ChatroomMessage
{
public class ChatroomMessage {
[Preserve]
[JsonProperty("username")]
public string Username { get; set; }
+1 -2
View File
@@ -1,5 +1,4 @@
public enum ColorObjectType
{
public enum ColorObjectType {
InGameBackgroundColor,
MenuBackgroundColor,
ButtonColor,
+1 -2
View File
@@ -3,8 +3,7 @@ using Newtonsoft.Json;
using UnityEngine.Scripting;
[Preserve]
public class LeaderboardEntry
{
public class LeaderboardEntry {
[Preserve]
[JsonProperty("id")]
public BigInteger UserID { get; set; }
+1 -2
View File
@@ -1,5 +1,4 @@
public enum LeaderboardMode
{
public enum LeaderboardMode {
None,
Score,
Berry,
+1 -2
View File
@@ -2,8 +2,7 @@ using Newtonsoft.Json;
using UnityEngine.Scripting;
[Preserve]
public class MarketplaceIcon
{
public class MarketplaceIcon {
[Preserve]
[JsonProperty("data")]
public string Data { get; set; }
@@ -2,8 +2,7 @@ using System.Collections.Generic;
using System.Numerics;
using Newtonsoft.Json;
public class MarketplaceIconStorageType
{
public class MarketplaceIconStorageType {
[JsonProperty("selected")]
public string Selected { get; set; } = null;
[JsonProperty("balance")]
@@ -3,8 +3,7 @@ using Newtonsoft.Json;
using UnityEngine.Scripting;
[Preserve]
public class MarketplaceIconWithData
{
public class MarketplaceIconWithData {
[Preserve]
[JsonProperty("username")]
public string CreatorUsername { get; set; }
+1 -2
View File
@@ -3,8 +3,7 @@ using Newtonsoft.Json;
using UnityEngine.Scripting;
[Preserve]
public class MarketplaceTempIcon
{
public class MarketplaceTempIcon {
[Preserve]
[JsonProperty("username")]
public string CreatorUsername { get; set; }
@@ -3,8 +3,7 @@ using Newtonsoft.Json;
using UnityEngine.Scripting;
[Preserve]
public class ProfileMessageResponse
{
public class ProfileMessageResponse {
[Preserve]
[JsonProperty("id")]
public BigInteger ID { get; set; }
+1 -2
View File
@@ -1,5 +1,4 @@
public enum SettingTypes
{
public enum SettingTypes {
FullScreen,
ShowFPS,
Vsync,
+1 -2
View File
@@ -3,8 +3,7 @@ using Newtonsoft.Json;
using UnityEngine.Scripting;
[Preserve]
public class Stats
{
public class Stats {
[Preserve]
[JsonProperty("highScore")]
public BigInteger HighScore { get; set; }
+14 -29
View File
@@ -6,8 +6,7 @@ using UnityEngine.Networking;
using UnityEngine.SceneManagement;
using UnityEngine.UI;
public class UserSearchMenu : MonoBehaviour
{
public class UserSearchMenu : MonoBehaviour {
[SerializeField] private GameObject content;
[SerializeField] private GameObject sampleObject;
[SerializeField] private Button searchButton;
@@ -15,15 +14,13 @@ public class UserSearchMenu : MonoBehaviour
[SerializeField] private TMP_Text statusText;
[SerializeField] private ProfileMenu profilePrefab;
void Awake()
{
void Awake() {
usernameInput.onSelect.AddListener((_) => usernameInput.caretPosition = usernameInput.text.Length);
searchButton.onClick.AddListener(Search);
Search();
}
async void Search()
{
async void Search() {
searchButton.interactable = false;
foreach (Transform item in content.transform)
if (item.gameObject.activeSelf)
@@ -33,18 +30,15 @@ public class UserSearchMenu : MonoBehaviour
request.SetRequestHeader("ClientVersion", Application.version);
request.SetRequestHeader("ClientPlatform", Application.platform.ToString());
await request.SendWebRequest();
if (request.downloadHandler.text == null)
{
if (request.downloadHandler.text == null) {
searchButton.interactable = true;
UpdateStatus(true, "Failed to get a list of users");
return;
}
UpdateStatus(false);
var jsonResponse = JObject.Parse(request.downloadHandler.text);
if ((bool)jsonResponse["success"])
{
foreach (var entry in jsonResponse["data"].ToObject<Account[]>())
{
if ((bool)jsonResponse["success"]) {
foreach (var entry in jsonResponse["data"].ToObject<Account[]>()) {
if (entry.UserID == BazookaManager.Instance.GetAccountID()) continue;
var entryInfo = Instantiate(sampleObject, content.transform);
var playerIcon = entryInfo.transform.GetChild(0).GetComponent<Image>();
@@ -56,8 +50,7 @@ public class UserSearchMenu : MonoBehaviour
usernameText.text = entry.Username;
highScoreText.text += Tools.FormatWithCommas(entry.Stats.HighScore);
if (entry.CustomIcon == null)
{
if (entry.CustomIcon == null) {
playerIcon.sprite = Resources.Load<Sprite>("Icons/Icons/bird_" + entry.Icon);
if (entry.Icon == 1) playerIcon.sprite = Tools.GetIconForUser(entry.UserID);
playerOverlay.sprite = Resources.Load<Sprite>("Icons/Overlays/overlay_" + entry.Overlay);
@@ -65,20 +58,16 @@ public class UserSearchMenu : MonoBehaviour
if (entry.Overlay == 8) playerOverlay.transform.localPosition = new Vector2(-16.56f, 14.81f);
else if (entry.Overlay == 11) playerOverlay.transform.localPosition = new Vector2(-14.74451f, 20.39122f);
else if (entry.Overlay == 13) playerOverlay.transform.localPosition = new Vector2(-16.54019f, 14.70365f);
try
{
try {
playerIcon.color = new Color(entry.BirdColor[0] / 255f, entry.BirdColor[1] / 255f, entry.BirdColor[2] / 255f);
playerOverlay.color = new Color(entry.BirdColor[0] / 255f, entry.BirdColor[1] / 255f, entry.BirdColor[2] / 255f);
}
catch
{
catch {
playerIcon.color = Color.white;
playerOverlay.color = Color.white;
}
}
else playerIcon.gameObject.AddComponent<WaitingForCustomIcon>().ID = entry.CustomIcon;
playerIconButton.onClick.AddListener(async () =>
{
} else playerIcon.gameObject.AddComponent<WaitingForCustomIcon>().ID = entry.CustomIcon;
playerIconButton.onClick.AddListener(async () => {
var clone = Instantiate(profilePrefab.gameObject, profilePrefab.gameObject.transform.parent);
clone.SetActive(true);
await clone.GetComponent<ProfileMenu>().Init(entry.UserID);
@@ -86,21 +75,17 @@ public class UserSearchMenu : MonoBehaviour
entryInfo.SetActive(true);
}
CustomIconLoader.Init(FindObjectsByType<WaitingForCustomIcon>(FindObjectsSortMode.None));
}
else
{
} else {
UpdateStatus(true, (string)jsonResponse["message"]);
}
searchButton.interactable = true;
}
async void Update()
{
async void Update() {
if (Keyboard.current.escapeKey.wasPressedThisFrame && !GameObject.Find("ProfilePrefab(Clone)")) await SceneManager.LoadSceneAsync("MainMenu");
}
private void UpdateStatus(bool enabled, string message = "")
{
private void UpdateStatus(bool enabled, string message = "") {
statusText.gameObject.SetActive(enabled);
statusText.text = message;
}
+2 -4
View File
@@ -1,11 +1,9 @@
using TMPro;
using UnityEngine;
public class VersionText : MonoBehaviour
{
public class VersionText : MonoBehaviour {
private TMP_Text text;
void Awake()
{
void Awake() {
text = gameObject.GetComponent<TMP_Text>();
text.text = "Current: v" + Application.version;
}
@@ -2,8 +2,7 @@ using System;
using UnityEngine;
[Serializable]
public class ConnectedWithCurrentSceneMessage
{
public class ConnectedWithCurrentSceneMessage {
public string type = "connected_with_current_scene";
public string sceneName;
public string Requester = "BerryDashClient";
+1 -2
View File
@@ -2,8 +2,7 @@ using System;
using Newtonsoft.Json.Linq;
[Serializable]
public class DeleteMessage
{
public class DeleteMessage {
public string type = "delete";
public string kind;
public JObject data;
+1 -2
View File
@@ -2,8 +2,7 @@ using System;
using Newtonsoft.Json.Linq;
[Serializable]
public class EditMessage
{
public class EditMessage {
public string type = "edit";
public string kind;
public JObject data;
@@ -1,8 +1,7 @@
using System;
[Serializable]
public class RequestInfoMessage
{
public class RequestInfoMessage {
public string type = "info_request";
public string kind;
public long timestamp = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
@@ -1,8 +1,7 @@
using System;
[Serializable]
public class SceneChangeMessage
{
public class SceneChangeMessage {
public string type = "scene_change";
public string to;
public string from;
+1 -2
View File
@@ -2,8 +2,7 @@ using System;
using Newtonsoft.Json.Linq;
[Serializable]
public class UploadMessage
{
public class UploadMessage {
public string type = "upload";
public string kind;
public JObject data;
+1 -2
View File
@@ -1,6 +1,5 @@
using UnityEngine;
public class WaitingForCustomIcon : MonoBehaviour
{
public class WaitingForCustomIcon : MonoBehaviour {
public string ID;
}
+17 -34
View File
@@ -3,8 +3,7 @@ using UnityEngine;
using System.Collections;
using UnityEngine.SceneManagement;
public class WebsocketHandler : MonoBehaviour
{
public class WebsocketHandler : MonoBehaviour {
public static WebsocketHandler Instance;
public WebSocketConnection _Connection;
@@ -14,10 +13,8 @@ public class WebsocketHandler : MonoBehaviour
private static readonly WaitForSeconds _waitForSeconds2 = new(2f);
private string lastSceneName = null;
private void Awake()
{
if (Instance != null)
{
private void Awake() {
if (Instance != null) {
Destroy(gameObject);
return;
}
@@ -26,8 +23,7 @@ public class WebsocketHandler : MonoBehaviour
DontDestroyOnLoad(gameObject);
_Connection = gameObject.AddComponent<WebSocketConnection>();
_Connection.DesiredConfig = new WebSocketConfig
{
_Connection.DesiredConfig = new WebSocketConfig {
MaxReceiveBytes = 10 * 1024 * 1024
};
_Connection.StateChanged += OnStateChanged;
@@ -38,17 +34,14 @@ public class WebsocketHandler : MonoBehaviour
Connect();
}
private void OnDestroy()
{
if (_Connection != null)
{
private void OnDestroy() {
if (_Connection != null) {
_Connection.StateChanged -= OnStateChanged;
_Connection.ErrorMessageReceived -= OnErrorMessageReceived;
}
}
public void Connect()
{
public void Connect() {
intentionalDisconnect = false;
if (_Connection.State == WebSocketState.Connected || _Connection.State == WebSocketState.Connecting) return;
@@ -56,37 +49,30 @@ public class WebsocketHandler : MonoBehaviour
_Connection.Connect(Endpoints.WS_ENDPOINT);
}
public void Disconnect()
{
public void Disconnect() {
intentionalDisconnect = true;
_Connection.Disconnect();
}
private void OnStateChanged(WebSocketConnection connection, WebSocketState oldState, WebSocketState newState)
{
private void OnStateChanged(WebSocketConnection connection, WebSocketState oldState, WebSocketState newState) {
Debug.Log($"WS state changed from \"{oldState}\" to \"{newState}\"");
if (newState == WebSocketState.Disconnected && !intentionalDisconnect && !isReconnecting)
{
if (newState == WebSocketState.Disconnected && !intentionalDisconnect && !isReconnecting) {
StartCoroutine(ReconnectWithDelay());
}
if (newState == WebSocketState.Connected)
{
if (newState == WebSocketState.Connected) {
var currentSceneName = SceneManager.GetActiveScene().name;
ConnectedWithCurrentSceneMessage msg = new()
{
ConnectedWithCurrentSceneMessage msg = new() {
sceneName = currentSceneName
};
_Connection.AddOutgoingMessage(JsonUtility.ToJson(msg));
}
}
private void OnErrorMessageReceived(WebSocketConnection connection, string errorMessage)
{
private void OnErrorMessageReceived(WebSocketConnection connection, string errorMessage) {
Debug.LogError($"WS error {errorMessage}");
}
private IEnumerator ReconnectWithDelay()
{
private IEnumerator ReconnectWithDelay() {
isReconnecting = true;
yield return _waitForSeconds2;
isReconnecting = false;
@@ -94,12 +80,9 @@ public class WebsocketHandler : MonoBehaviour
Connect();
}
private void OnSceneLoaded(Scene scene, LoadSceneMode mode)
{
if (_Connection.State == WebSocketState.Connected)
{
SceneChangeMessage msg = new()
{
private void OnSceneLoaded(Scene scene, LoadSceneMode mode) {
if (_Connection.State == WebSocketState.Connected) {
SceneChangeMessage msg = new() {
to = scene.name,
from = lastSceneName
};