change: Switched the state controller and scene controller to a singleton class

This doesnt' change any of the logic, but simplifies a lot of the main
game loop code.

Many things still rely on the singleton class, but shouldn't so this
will be fixed in a later commit
This commit is contained in:
Nicholas Novak 2023-05-04 02:19:51 -07:00
parent afbcb920ac
commit 5a7ce8fb2b
8 changed files with 301 additions and 211 deletions

View File

@ -6,26 +6,21 @@ using TMPro;
public class DebugSceneSwitcher : MonoBehaviour public class DebugSceneSwitcher : MonoBehaviour
{ {
void Awake()
void Awake() { {
if (!GameObject.Find("StateController").GetComponent<StateController>().inDebugMode) { // Keep the object around when we switch scenes
Destroy(this.gameObject);
}
// check to see if a debug canvas already exists
if (GameObject.FindGameObjectWithTag("DebugCanvas") != null) {
Destroy(this.gameObject);
} else { // if it doesn't, then this is the only one
this.gameObject.tag = "DebugCanvas";
}
DontDestroyOnLoad(this.gameObject); DontDestroyOnLoad(this.gameObject);
CreateDropdownOptions(); CreateDropdownOptions();
} }
void CreateDropdownOptions() { void CreateDropdownOptions()
{
TMP_Dropdown sceneDropdown = GameObject.Find("SceneSwitcherDropdown").GetComponent<TMP_Dropdown>(); TMP_Dropdown sceneDropdown = GameObject.Find("SceneSwitcherDropdown").GetComponent<TMP_Dropdown>();
if (sceneDropdown.options.Count == 0) { if (sceneDropdown.options.Count == 0)
{
List<string> sceneNames = new List<string>(); List<string> sceneNames = new List<string>();
for (int i = 0; i < SceneManager.sceneCountInBuildSettings; i++) { for (int i = 0; i < SceneManager.sceneCountInBuildSettings; i++)
{
string newName = System.IO.Path.GetFileNameWithoutExtension(SceneUtility.GetScenePathByBuildIndex(i)); string newName = System.IO.Path.GetFileNameWithoutExtension(SceneUtility.GetScenePathByBuildIndex(i));
print(newName); print(newName);
sceneNames.Add(newName); sceneNames.Add(newName);
@ -34,9 +29,10 @@ public class DebugSceneSwitcher : MonoBehaviour
} }
} }
public void ChangeScene(int index) { public void ChangeScene(int index)
{
// print(index); // print(index);
GameObject.FindGameObjectWithTag("SceneManager").GetComponent<SceneController>().LoadChosenScene(index);
this.gameObject.SetActive(false); this.gameObject.SetActive(false);
SceneController.Instance.LoadChosenScene(index);
} }
} }

View File

@ -26,31 +26,40 @@ public class DialogBoxes : MonoBehaviour
textField.text = dialogMessages[0]; textField.text = dialogMessages[0];
backgroundImageObject.sprite = images[0]; backgroundImageObject.sprite = images[0];
} }
void OnAdvanceDialog() { void OnAdvanceDialog()
{
messageCount += 1; messageCount += 1;
if (messageCount < dialogMessages.Length) { if (messageCount < dialogMessages.Length)
{
textField.text = dialogMessages[messageCount]; textField.text = dialogMessages[messageCount];
backgroundImageObject.sprite = images[messageCount]; backgroundImageObject.sprite = images[messageCount];
} else { // no more dialog messages, advance the scene }
GameObject.Find("SceneManager").GetComponent<SceneController>().NextScene(); else
{ // no more dialog messages, advance the scene
SceneController.Instance.NextScene();
} }
} }
void ReconfigureSpriteArray() { void ReconfigureSpriteArray()
{
// resize if need to // resize if need to
if (images.Length != dialogMessages.Length) { if (images.Length != dialogMessages.Length)
{
Sprite[] newImagesArray = new Sprite[dialogMessages.Length]; Sprite[] newImagesArray = new Sprite[dialogMessages.Length];
for (int i = 0; i < newImagesArray.Length; i++) { for (int i = 0; i < newImagesArray.Length; i++)
{
newImagesArray[i] = images[i]; newImagesArray[i] = images[i];
} }
images = newImagesArray; images = newImagesArray;
} }
// update empty slots // update empty slots
for (int i = 1; i < images.Length; i++) { for (int i = 1; i < images.Length; i++)
if (images[i] == null ) { {
images[i] = images[i-1]; if (images[i] == null)
{
images[i] = images[i - 1];
} }
} }

View File

@ -14,64 +14,50 @@ public class GameUIController : MonoBehaviour
[HideInInspector] public GameObject tambourineUI; [HideInInspector] public GameObject tambourineUI;
[HideInInspector] public GameObject clarinetUI; [HideInInspector] public GameObject clarinetUI;
[Header("Other Objects")] void Start()
private StateController stateController; {
this.trumpetUI = trumpetBackground.transform.GetChild(0).gameObject;
this.tambourineUI = tambourineBackground.transform.GetChild(0).gameObject;
this.clarinetUI = clarinetBackground.transform.GetChild(0).gameObject;
void Start() {
stateController = GameObject.FindGameObjectWithTag("StateController").GetComponent<StateController>();
if (stateController == null) {
print("state controller not found");
} else {
print("yeehaw");
}
trumpetUI = trumpetBackground.transform.GetChild(0).gameObject;
tambourineUI = tambourineBackground.transform.GetChild(0).gameObject;
clarinetUI = clarinetBackground.transform.GetChild(0).gameObject;
if (!stateController.unlockedTrumpet) { // TODO: This can be probably be combined with the update methods
trumpetBackground.SetActive(false); this.trumpetBackground.SetActive(StateController.Instance.HasTrumpet());
} this.tambourineBackground.SetActive(StateController.Instance.HasTambourine());
if (!stateController.unlockedTambourine) { this.clarinetBackground.SetActive(StateController.Instance.HasClarinet());
tambourineBackground.SetActive(false);
}
if (!stateController.unlockedClarinet) {
clarinetBackground.SetActive(false);
}
} }
public void ToggleTrumpet(bool toggleState) { public void ToggleTrumpet(bool toggleState)
{
bool curEnabled = trumpetUI.GetComponent<Image>().enabled; bool curEnabled = trumpetUI.GetComponent<Image>().enabled;
if (curEnabled != toggleState) { if (curEnabled != toggleState)
{
trumpetUI.GetComponent<Image>().enabled = toggleState; trumpetUI.GetComponent<Image>().enabled = toggleState;
} }
} }
public void ToggleTambourine(bool toggleState) { public void ToggleTambourine(bool toggleState)
{
bool curEnabled = tambourineUI.GetComponent<Image>().enabled; bool curEnabled = tambourineUI.GetComponent<Image>().enabled;
if (curEnabled != toggleState) { if (curEnabled != toggleState)
{
tambourineUI.GetComponent<Image>().enabled = toggleState; tambourineUI.GetComponent<Image>().enabled = toggleState;
} }
} }
public void ToggleClarinet(bool toggleState) { public void ToggleClarinet(bool toggleState)
{
bool curEnabled = clarinetUI.GetComponent<Image>().enabled; bool curEnabled = clarinetUI.GetComponent<Image>().enabled;
if (curEnabled != toggleState) { if (curEnabled != toggleState)
{
clarinetUI.GetComponent<Image>().enabled = toggleState; clarinetUI.GetComponent<Image>().enabled = toggleState;
} }
} }
public void ResetInstrumentUI() { public void UpdateInstrumentUI()
if (stateController == null) { {
print("state controller null"); this.ToggleTrumpet(StateController.Instance.HasTrumpet());
} this.ToggleTambourine(StateController.Instance.HasTambourine());
if (stateController.unlockedTrumpet) { this.ToggleClarinet(StateController.Instance.HasClarinet());
ToggleTrumpet(true);
}
if (stateController.unlockedTambourine) {
ToggleTambourine(true);
}
if (stateController.unlockedClarinet) {
ToggleClarinet(true);
}
} }
} }

View File

@ -33,7 +33,6 @@ public class PlayerBehavior : MonoBehaviour
[Header("Controllers:")] [Header("Controllers:")]
[SerializeField] private PlayerMovement playerController; [SerializeField] private PlayerMovement playerController;
[SerializeField] private StateController stateController;
private GameUIController gameUI; private GameUIController gameUI;
Animator animator; Animator animator;
@ -43,12 +42,11 @@ public class PlayerBehavior : MonoBehaviour
[SerializeField] public AudioClip footstepSound; [SerializeField] public AudioClip footstepSound;
[SerializeField] public AudioClip deathSound; [SerializeField] public AudioClip deathSound;
AudioSource audioSource; AudioSource audioSource;
void Awake() void Awake()
{ // initialize { // initialize
_rb = GetComponent<Rigidbody2D>(); _rb = GetComponent<Rigidbody2D>();
stateController = GameObject.Find("StateController").GetComponent<StateController>();
gameUI = GameObject.FindGameObjectWithTag("GameUICanvas").GetComponent<GameUIController>(); gameUI = GameObject.FindGameObjectWithTag("GameUICanvas").GetComponent<GameUIController>();
@ -61,18 +59,19 @@ public class PlayerBehavior : MonoBehaviour
playerIsAlive = true; playerIsAlive = true;
} }
void Start() { void Start()
gameUI.ResetInstrumentUI(); {
gameUI.UpdateInstrumentUI();
// for clarinet // for clarinet
currentDashTime = maxDashTime; currentDashTime = maxDashTime;
} }
void Update() void Update()
{ {
unlockedTambourine = stateController.unlockedTambourine; unlockedTambourine = StateController.Instance.HasTambourine();
if (playerIsAlive) { if (playerIsAlive)
{
// throw tambourine // throw tambourine
// if (Input.GetKeyDown(KeyCode.K)) {
if (playerInput.actions["ThrowTambourine"].WasPressedThisFrame()) if (playerInput.actions["ThrowTambourine"].WasPressedThisFrame())
{ {
ThrowTambourine(); ThrowTambourine();
@ -80,12 +79,10 @@ public class PlayerBehavior : MonoBehaviour
// grapple // grapple
tambourine = GameObject.FindGameObjectWithTag("tambourine"); tambourine = GameObject.FindGameObjectWithTag("tambourine");
// if (Input.GetKeyDown(KeyCode.L)) {
if (playerInput.actions["Grapple"].WasPressedThisFrame()) if (playerInput.actions["Grapple"].WasPressedThisFrame())
{ {
AttemptGrapple(); AttemptGrapple();
} }
// if (Input.GetKeyUp(KeyCode.L)) {
if (playerInput.actions["Grapple"].WasReleasedThisFrame()) if (playerInput.actions["Grapple"].WasReleasedThisFrame())
{ {
LetGoOfGrapple(); LetGoOfGrapple();
@ -94,8 +91,8 @@ public class PlayerBehavior : MonoBehaviour
Animate(); Animate();
} }
unlockedClarinet = stateController.unlockedClarinet; unlockedClarinet = StateController.Instance.HasClarinet();
if(playerIsAlive && unlockedClarinet) if (playerIsAlive && unlockedClarinet)
{ {
if (playerInput.actions["ClarinetDive"].WasPressedThisFrame()) if (playerInput.actions["ClarinetDive"].WasPressedThisFrame())
{ {
@ -125,31 +122,37 @@ public class PlayerBehavior : MonoBehaviour
} }
} }
void Animate() { void Animate()
{
// start walking // start walking
if (playerInput.actions["Move"].WasPressedThisFrame()) { if (playerInput.actions["Move"].WasPressedThisFrame())
{
animator.SetBool("Walking", true); animator.SetBool("Walking", true);
} }
// return to idle animation // return to idle animation
if (playerInput.actions["Move"].WasReleasedThisFrame()) { if (playerInput.actions["Move"].WasReleasedThisFrame())
{
animator.SetBool("Walking", false); animator.SetBool("Walking", false);
} }
} }
void OnMove(InputValue value) void OnMove(InputValue value)
{ {
if (playerIsAlive) { if (playerIsAlive)
{
_hInput = value.Get<Vector2>().x; _hInput = value.Get<Vector2>().x;
if (_hInput < 0) if (_hInput < 0)
{ {
if (forward != -1) { // if character hasnt already flipped if (forward != -1)
{ // if character hasnt already flipped
FlipRenderer(); FlipRenderer();
} }
forward = -1; forward = -1;
} }
else if (_hInput > 0) else if (_hInput > 0)
{ {
if (forward != 1) { // if character hasnt already flipped if (forward != 1)
{ // if character hasnt already flipped
FlipRenderer(); FlipRenderer();
} }
forward = 1; forward = 1;
@ -158,30 +161,35 @@ public class PlayerBehavior : MonoBehaviour
} }
void FlipScale() { // DOENST WORK RIGHT (that's so sad for you) void FlipScale()
{ // DOENST WORK RIGHT (that's so sad for you)
Vector3 currentScale = this.gameObject.transform.localScale; Vector3 currentScale = this.gameObject.transform.localScale;
currentScale.x *= -1; currentScale.x *= -1;
this.gameObject.transform.localScale = currentScale; this.gameObject.transform.localScale = currentScale;
} }
void FlipRenderer() { void FlipRenderer()
{
GetComponent<SpriteRenderer>().flipX = !GetComponent<SpriteRenderer>().flipX; GetComponent<SpriteRenderer>().flipX = !GetComponent<SpriteRenderer>().flipX;
} }
void ThrowTambourine() { void ThrowTambourine()
{
if (unlockedTambourine && hasTambourine && !grapplingRope.isGrappling) if (unlockedTambourine && hasTambourine && !grapplingRope.isGrappling)
{ {
launcher.ThrowTambourine(forward); launcher.ThrowTambourine(forward);
SetHasTambourine(false); SetHasTambourine(false);
} }
} }
public void SetHasTambourine(bool state) { public void SetHasTambourine(bool state)
{
hasTambourine = state; hasTambourine = state;
gameUI.ToggleTambourine(state); gameUI.ToggleTambourine(state);
} }
void AttemptGrapple() { void AttemptGrapple()
{
if (tambourine != null) if (tambourine != null)
{ // grapple to tambourine { // grapple to tambourine
if (!grapplingRope.isGrappling && tambourine.GetComponent<TambourineBehavior>().pinned) if (!grapplingRope.isGrappling && tambourine.GetComponent<TambourineBehavior>().pinned)
@ -200,11 +208,14 @@ public class PlayerBehavior : MonoBehaviour
} }
} }
void LetGoOfGrapple() { void LetGoOfGrapple()
bool currentlyPaused = stateController.isPaused; {
if (grapplingRope.isGrappling && !currentlyPaused) { bool currentlyPaused = StateController.Instance.isPaused;
if (grapplingRope.isGrappling && !currentlyPaused)
{
print("currently paused is " + currentlyPaused + ", releasing grapple"); print("currently paused is " + currentlyPaused + ", releasing grapple");
if (tambourine != null) { if (tambourine != null)
{
tambourine.GetComponent<TambourineBehavior>().DestroySelf(); tambourine.GetComponent<TambourineBehavior>().DestroySelf();
} }
grapplingGun.ReleaseGrapple(); grapplingGun.ReleaseGrapple();
@ -222,8 +233,9 @@ public class PlayerBehavior : MonoBehaviour
print("player fell in spikes"); print("player fell in spikes");
StartCoroutine(DestroyPlayer()); StartCoroutine(DestroyPlayer());
} }
else if (col.tag == "spawnPoint") { else if (col.tag == "spawnPoint")
stateController.spawnPoint.GetComponent<SpawnPointBehavior>().DeactivateSpawnPoint(); {
StateController.Instance.spawnPoint.GetComponent<SpawnPointBehavior>().DeactivateSpawnPoint();
col.GetComponent<SpawnPointBehavior>().ActivateSpawnPoint(); col.GetComponent<SpawnPointBehavior>().ActivateSpawnPoint();
} }
else if (col.tag == "Trumpet") else if (col.tag == "Trumpet")
@ -246,17 +258,23 @@ public class PlayerBehavior : MonoBehaviour
} }
} }
void OnCollisionEnter2D(Collision2D collision) { void OnCollisionEnter2D(Collision2D collision)
if (collision.gameObject.tag == "Enemy" || collision.gameObject.tag == "ProjectileEnemy") { {
if (collision.transform.position.y < transform.position.y) { if (collision.gameObject.tag == "Enemy" || collision.gameObject.tag == "ProjectileEnemy")
{
if (collision.transform.position.y < transform.position.y)
{
_rb.AddForce(Vector2.up * 8, ForceMode2D.Impulse); _rb.AddForce(Vector2.up * 8, ForceMode2D.Impulse);
collision.gameObject.GetComponent<EnemyPatrol>().DefeatEnemy(); collision.gameObject.GetComponent<EnemyPatrol>().DefeatEnemy();
} else { }
else
{
StartCoroutine(DestroyPlayer()); StartCoroutine(DestroyPlayer());
print("enemy defeated player"); print("enemy defeated player");
} }
} }
else if (collision.gameObject.tag == "Projectile") { else if (collision.gameObject.tag == "Projectile")
{
Destroy(collision.gameObject); Destroy(collision.gameObject);
StartCoroutine(DestroyPlayer()); StartCoroutine(DestroyPlayer());
} }
@ -267,12 +285,14 @@ public class PlayerBehavior : MonoBehaviour
} }
else if (collision.gameObject.tag == "Door") else if (collision.gameObject.tag == "Door")
{ {
this.stateController.RespawnPlayer(); StateController.Instance.RespawnPlayer();
} }
} }
IEnumerator DestroyPlayer() { IEnumerator DestroyPlayer()
if (playerIsAlive) { {
if (playerIsAlive)
{
print("destroyPlayer called"); print("destroyPlayer called");
playerIsAlive = false; playerIsAlive = false;
audioSource.clip = deathSound; audioSource.clip = deathSound;
@ -288,12 +308,13 @@ public class PlayerBehavior : MonoBehaviour
// destroy all tambourines // destroy all tambourines
GameObject[] currentTambourines = GameObject.FindGameObjectsWithTag("tambourine"); GameObject[] currentTambourines = GameObject.FindGameObjectsWithTag("tambourine");
foreach (GameObject tambourine in currentTambourines) { foreach (GameObject tambourine in currentTambourines)
{
tambourine.GetComponent<TambourineBehavior>().DestroySelf(); tambourine.GetComponent<TambourineBehavior>().DestroySelf();
// Destroy(tambourine); // Destroy(tambourine);
} }
this.stateController.RespawnPlayer(); StateController.Instance.RespawnPlayer();
} }
} }
} }

View File

@ -65,8 +65,8 @@ public class PlayerMovement : MonoBehaviour
[Header("Layers & Tags")] [Header("Layers & Tags")]
[SerializeField] private LayerMask _groundLayer; [SerializeField] private LayerMask _groundLayer;
// Static classes
[HideInInspector] private PlayerBehavior playerBehavior; [HideInInspector] private PlayerBehavior playerBehavior;
[HideInInspector] private StateController stateController;
[HideInInspector] private AudioSource audioSource; [HideInInspector] private AudioSource audioSource;
[HideInInspector] private bool soundPlaying = false; [HideInInspector] private bool soundPlaying = false;
@ -79,7 +79,6 @@ public class PlayerMovement : MonoBehaviour
RB = GetComponent<Rigidbody2D>(); RB = GetComponent<Rigidbody2D>();
playerBehavior = this.gameObject.GetComponent<PlayerBehavior>(); playerBehavior = this.gameObject.GetComponent<PlayerBehavior>();
grapplingRope = playerBehavior.grapplingRope; grapplingRope = playerBehavior.grapplingRope;
stateController = GameObject.FindGameObjectWithTag("StateController").GetComponent<StateController>();
audioSource = GetComponent<AudioSource>(); audioSource = GetComponent<AudioSource>();
gameUI = GameObject.FindGameObjectWithTag("GameUICanvas").GetComponent<GameUIController>(); gameUI = GameObject.FindGameObjectWithTag("GameUICanvas").GetComponent<GameUIController>();
trumpetSprite.enabled = false; trumpetSprite.enabled = false;
@ -93,16 +92,20 @@ public class PlayerMovement : MonoBehaviour
void OnMove(InputValue value) void OnMove(InputValue value)
{ {
if (playerBehavior.playerIsAlive) { if (playerBehavior.playerIsAlive)
{
this._moveInput = value.Get<Vector2>(); this._moveInput = value.Get<Vector2>();
} else { }
else
{
this._moveInput = Vector2.zero; this._moveInput = Vector2.zero;
} }
} }
void OnJump() void OnJump()
{ {
if (playerBehavior.playerIsAlive) { if (playerBehavior.playerIsAlive)
{
OnJumpInput(); OnJumpInput();
} }
} }
@ -141,21 +144,30 @@ public class PlayerMovement : MonoBehaviour
if (IsGrounded()) //checks if set box overlaps with ground if (IsGrounded()) //checks if set box overlaps with ground
{ {
LastOnGroundTime = Data.coyoteTime; //if so sets the lastGrounded to coyoteTime LastOnGroundTime = Data.coyoteTime; //if so sets the lastGrounded to coyoteTime
if (unlockedTrumpet) { if (unlockedTrumpet)
{
trumpet = 2; trumpet = 2;
gameUI.ToggleTrumpet(true); gameUI.ToggleTrumpet(true);
} else { }
else
{
trumpet = -1; trumpet = -1;
} }
wasGrappling = false; wasGrappling = false;
isRegFalling = false; isRegFalling = false;
} else { }
else
{
// print("not jumping"); // print("not jumping");
if(!_isJumpFalling && !isRegFalling) { if (!_isJumpFalling && !isRegFalling)
if(unlockedTrumpet) { {
if (unlockedTrumpet)
{
trumpet = 1; trumpet = 1;
gameUI.ToggleTrumpet(true); gameUI.ToggleTrumpet(true);
} else { }
else
{
trumpet = -1; trumpet = -1;
} }
isRegFalling = true; isRegFalling = true;
@ -208,7 +220,7 @@ public class PlayerMovement : MonoBehaviour
_isJumpCut = false; _isJumpCut = false;
_isJumpFalling = false; _isJumpFalling = false;
Jump(); Jump();
// determine if trumpet jump // determine if trumpet jump
if (!IsGrounded() && in_range && trumpet > 0) if (!IsGrounded() && in_range && trumpet > 0)
{ {
@ -223,14 +235,16 @@ public class PlayerMovement : MonoBehaviour
trumpet -= 1; trumpet -= 1;
} }
// check if double jump, play sound // check if double jump, play sound
if (trumpet == 0) { if (trumpet == 0)
{
StartCoroutine(ActivateTrumpetSprite()); StartCoroutine(ActivateTrumpetSprite());
gameObject.transform.Find("Trumpet").GetComponent<AudioSource>().Play(); gameObject.transform.Find("Trumpet").GetComponent<AudioSource>().Play();
} }
} }
// stop sound if needed // stop sound if needed
if (soundPlaying && (isRegFalling || IsJumping || _isJumpFalling)) { if (soundPlaying && (isRegFalling || IsJumping || _isJumpFalling))
{
print("footsteps stop"); print("footsteps stop");
audioSource.Stop(); audioSource.Stop();
soundPlaying = false; soundPlaying = false;
@ -252,7 +266,8 @@ public class PlayerMovement : MonoBehaviour
#region GRAPPLE CHECKS #region GRAPPLE CHECKS
// set wasGrappling to true if the player starts grappling // set wasGrappling to true if the player starts grappling
if (grapplingRope.isGrappling) { if (grapplingRope.isGrappling)
{
wasGrappling = true; wasGrappling = true;
} }
#endregion #endregion
@ -303,13 +318,17 @@ public class PlayerMovement : MonoBehaviour
#endregion #endregion
#region SOUND CHECKS #region SOUND CHECKS
if (!IsJumping && !_isJumpFalling && !isRegFalling && _moveInput.x != 0) { if (!IsJumping && !_isJumpFalling && !isRegFalling && _moveInput.x != 0)
if (!soundPlaying) { {
if (!soundPlaying)
{
// print("footsteps PLAY"); // print("footsteps PLAY");
audioSource.Play(); audioSource.Play();
soundPlaying = true; soundPlaying = true;
} }
} else if (soundPlaying && audioSource.clip.name == "footsteps") { }
else if (soundPlaying && audioSource.clip.name == "footsteps")
{
// print("footsteps stop"); // print("footsteps stop");
audioSource.Stop(); audioSource.Stop();
soundPlaying = false; soundPlaying = false;
@ -317,7 +336,8 @@ public class PlayerMovement : MonoBehaviour
#endregion #endregion
#region UPDATE UI #region UPDATE UI
if (trumpet == 0) { if (trumpet == 0)
{
gameUI.ToggleTrumpet(false); gameUI.ToggleTrumpet(false);
} }
#endregion #endregion
@ -371,12 +391,16 @@ public class PlayerMovement : MonoBehaviour
//Gets an acceleration value based on if we are accelerating (includes turning) //Gets an acceleration value based on if we are accelerating (includes turning)
//or trying to decelerate (stop). As well as applying a multiplier if we're air borne. //or trying to decelerate (stop). As well as applying a multiplier if we're air borne.
if (LastOnGroundTime > 0) { if (LastOnGroundTime > 0)
{
accelRate = (Mathf.Abs(targetSpeed) > 0.01f) ? Data.runAccelAmount : Data.runDeccelAmount; accelRate = (Mathf.Abs(targetSpeed) > 0.01f) ? Data.runAccelAmount : Data.runDeccelAmount;
} }
else if (wasGrappling) { else if (wasGrappling)
{
accelRate = (Mathf.Abs(targetSpeed) > 0.01f) ? Data.runAccelAmount * Data.accelInAir : Data.runDeccelAmount * (Data.deccelInAir / 5); accelRate = (Mathf.Abs(targetSpeed) > 0.01f) ? Data.runAccelAmount * Data.accelInAir : Data.runDeccelAmount * (Data.deccelInAir / 5);
} else { }
else
{
accelRate = (Mathf.Abs(targetSpeed) > 0.01f) ? Data.runAccelAmount * Data.accelInAir : Data.runDeccelAmount * Data.deccelInAir; accelRate = (Mathf.Abs(targetSpeed) > 0.01f) ? Data.runAccelAmount * Data.accelInAir : Data.runDeccelAmount * Data.deccelInAir;
} }
#endregion #endregion
@ -410,10 +434,10 @@ public class PlayerMovement : MonoBehaviour
RB.AddForce(movement * Vector2.right, ForceMode2D.Force); RB.AddForce(movement * Vector2.right, ForceMode2D.Force);
/* /*
* For those interested here is what AddForce() will do * For those interested here is what AddForce() will do
* RB.velocity = new Vector2(RB.velocity.x + (Time.fixedDeltaTime * speedDif * accelRate) / RB.mass, RB.velocity.y); * RB.velocity = new Vector2(RB.velocity.x + (Time.fixedDeltaTime * speedDif * accelRate) / RB.mass, RB.velocity.y);
* Time.fixedDeltaTime is by default in Unity 0.02 seconds equal to 50 FixedUpdate() calls per second * Time.fixedDeltaTime is by default in Unity 0.02 seconds equal to 50 FixedUpdate() calls per second
*/ */
} }
private void Turn() private void Turn()
@ -547,8 +571,10 @@ public class PlayerMovement : MonoBehaviour
#endregion #endregion
#region ADDITIONAL TRUMPET METHODS #region ADDITIONAL TRUMPET METHODS
IEnumerator ActivateTrumpetSprite() { IEnumerator ActivateTrumpetSprite()
if (!trumpetActive) { {
if (!trumpetActive)
{
trumpetActive = true; trumpetActive = true;
trumpetSprite.enabled = true; trumpetSprite.enabled = true;
yield return new WaitForSeconds(.5f); yield return new WaitForSeconds(.5f);

View File

@ -7,38 +7,46 @@ using UnityEngine.UI;
public class SceneController : MonoBehaviour public class SceneController : MonoBehaviour
{ {
public static SceneController Instance = null;
// this object will always exist! // this object will always exist!
void Awake() { void Awake()
// check to see if a state controller already exists {
if (GameObject.FindGameObjectWithTag("SceneManager") != null) { if (Instance == null)
Destroy(this.gameObject); {
} else { // if it doesn't, then this is the only one Instance = this;
this.gameObject.tag = "SceneManager";
} }
// Make this object stay around when switching scenes
DontDestroyOnLoad(this.gameObject); DontDestroyOnLoad(this.gameObject);
SceneManager.sceneLoaded += OnSceneLoaded; SceneManager.sceneLoaded += OnSceneLoaded;
} }
void OnSceneLoaded(Scene scene, LoadSceneMode mode) { void OnSceneLoaded(Scene scene, LoadSceneMode mode)
{
GameObject pauseMenu = GameObject.Find("PauseMenuCanvas"); GameObject pauseMenu = GameObject.Find("PauseMenuCanvas");
if (pauseMenu != null) { if (pauseMenu != null)
{
Button quitButton = GameObject.Find("QuitButton").GetComponent<Button>(); Button quitButton = GameObject.Find("QuitButton").GetComponent<Button>();
quitButton.onClick.AddListener(BackToMainMenu); quitButton.onClick.AddListener(BackToMainMenu);
} }
if (scene.buildIndex == 0) { // if this is the menu if (scene.buildIndex == 0)
{ // if this is the menu
GameObject.Find("NewGameButton").GetComponent<Button>().onClick.AddListener(NextScene); GameObject.Find("NewGameButton").GetComponent<Button>().onClick.AddListener(NextScene);
} }
} }
public void NextScene() { public void NextScene()
{
SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex + 1); SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex + 1);
} }
public void BackToMainMenu() { public void BackToMainMenu()
{
SceneManager.LoadScene(0); // main menu scene should be 0 SceneManager.LoadScene(0); // main menu scene should be 0
} }
public void LoadChosenScene(int index) { public void LoadChosenScene(int index)
{
SceneManager.LoadScene(index); SceneManager.LoadScene(index);
} }

View File

@ -4,7 +4,19 @@ using UnityEngine;
using UnityEngine.SceneManagement; using UnityEngine.SceneManagement;
using UnityEngine.UI; using UnityEngine.UI;
public class StateController : MonoBehaviour { public enum UnlockedItems
{
None,
Trumpet,
Tambourine,
Clarinet,
}
public class StateController : MonoBehaviour
{
// Singleton class
public static StateController Instance = null;
[Header("Respawning")] [Header("Respawning")]
[SerializeField] GameObject player; [SerializeField] GameObject player;
@ -17,7 +29,7 @@ public class StateController : MonoBehaviour {
[Header("Debug")] [Header("Debug")]
public bool inDebugMode; public bool inDebugMode;
GameObject debugCanvas; public GameObject debugCanvas;
[Header("Enemies")] [Header("Enemies")]
GameObject[] enemiesInScene; GameObject[] enemiesInScene;
@ -26,33 +38,53 @@ public class StateController : MonoBehaviour {
GameObject victoryCanvas; GameObject victoryCanvas;
[Header("Unlocked Items")] [Header("Unlocked Items")]
[SerializeField] public bool unlockedTrumpet = false; public UnlockedItems itemProgression = UnlockedItems.None;
[SerializeField] public bool unlockedTambourine = false;
[SerializeField] public bool unlockedClarinet = false;
void Awake() { void Awake()
// check to see if a state controller already exists {
if (GameObject.FindGameObjectWithTag("StateController") != null) { // TODO: Remove this when done
Destroy(this.gameObject); AudioListener.pause = true;
} else { // if it doesn't, then this is the only one if (Instance == null)
this.gameObject.tag = "StateController"; {
Instance = this;
} }
DontDestroyOnLoad(this.gameObject); //DontDestroyOnLoad(this.gameObject);
SceneManager.sceneLoaded += OnSceneLoaded; SceneManager.sceneLoaded += OnSceneLoaded;
if (inDebugMode) { if (this.inDebugMode)
{
debugCanvas = GameObject.Find("DebugCanvas"); debugCanvas = GameObject.Find("DebugCanvas");
debugCanvas.SetActive(false); debugCanvas.SetActive(false);
} }
} }
void OnSceneLoaded(Scene scene, LoadSceneMode mode) { public bool HasTrumpet()
{
return this.itemProgression >= UnlockedItems.Trumpet;
}
public bool HasTambourine()
{
return this.itemProgression >= UnlockedItems.Tambourine;
}
public bool HasClarinet()
{
return this.itemProgression >= UnlockedItems.Clarinet;
}
void OnSceneLoaded(Scene scene, LoadSceneMode mode)
{
#region FIND OBJECTS #region FIND OBJECTS
deathCanvas = GameObject.Find("DeathUICanvas"); deathCanvas = GameObject.Find("DeathUICanvas");
if (deathCanvas != null) { if (deathCanvas != null)
{
Button respawnButton = GameObject.Find("RespawnButton").GetComponent<Button>(); Button respawnButton = GameObject.Find("RespawnButton").GetComponent<Button>();
if (respawnButton == null) { if (respawnButton == null)
{
print("respawn button not found!"); print("respawn button not found!");
} }
respawnButton.onClick.AddListener(RespawnPlayer); respawnButton.onClick.AddListener(RespawnPlayer);
@ -60,14 +92,16 @@ public class StateController : MonoBehaviour {
} }
pauseMenuCanvas = GameObject.Find("PauseMenuCanvas"); pauseMenuCanvas = GameObject.Find("PauseMenuCanvas");
if (pauseMenuCanvas != null) { if (pauseMenuCanvas != null)
{
Button resumeButton = GameObject.Find("ResumeButton").GetComponent<Button>(); Button resumeButton = GameObject.Find("ResumeButton").GetComponent<Button>();
resumeButton.onClick.AddListener(Unpause); resumeButton.onClick.AddListener(Unpause);
TogglePauseMenu(false); TogglePauseMenu(false);
} }
victoryCanvas = GameObject.Find("VictoryCanvas"); victoryCanvas = GameObject.Find("VictoryCanvas");
if (victoryCanvas != null) { if (victoryCanvas != null)
{
Button continueButton = GameObject.Find("ContinueButton").GetComponent<Button>(); Button continueButton = GameObject.Find("ContinueButton").GetComponent<Button>();
continueButton.onClick.AddListener(ContinueToNextLevel); continueButton.onClick.AddListener(ContinueToNextLevel);
victoryCanvas.SetActive(false); victoryCanvas.SetActive(false);
@ -77,49 +111,47 @@ public class StateController : MonoBehaviour {
enemiesInScene = GameObject.FindGameObjectsWithTag("Enemy"); enemiesInScene = GameObject.FindGameObjectsWithTag("Enemy");
// print(enemiesInScene); // print(enemiesInScene);
if (isPaused) { if (isPaused)
{
Unpause(); Unpause();
} }
#endregion #endregion
#region UNLOCK ITEMS #region UNLOCK ITEMS
if (SceneManager.GetActiveScene().name == "GrenouilleVillage") { switch (SceneManager.GetActiveScene().name)
unlockedTrumpet = false;
unlockedTambourine = false;
unlockedClarinet = false;
}
else if (SceneManager.GetActiveScene().name == "Brasslands")
{ {
unlockedTrumpet = true; case "GrenouilleVillage":
unlockedTambourine = false; this.itemProgression = UnlockedItems.None;
unlockedClarinet = false; break;
} case "GrappleScene":
else if (SceneManager.GetActiveScene().name == "GrappleScene") { this.itemProgression = UnlockedItems.Trumpet;
unlockedTrumpet = true; break;
unlockedTambourine = true; case "ClarinetScene":
unlockedClarinet = false; this.itemProgression = UnlockedItems.Clarinet;
} break;
else if (SceneManager.GetActiveScene().name == "ClarinetScene") { };
unlockedTrumpet = true;
unlockedTambourine = true;
unlockedClarinet = true;
}
#endregion #endregion
} }
void OnToggleDebugMenu() { void OnToggleDebugMenu()
if (inDebugMode) { {
debugCanvas.SetActive(!debugCanvas.activeSelf); if (inDebugMode)
{
debugCanvas.SetActive(!this.debugCanvas.activeSelf);
} }
} }
void OnPause() { void OnPause()
if (pauseMenuCanvas != null) { {
if (!isPaused) { if (pauseMenuCanvas != null)
{
if (!isPaused)
{
Time.timeScale = 0; Time.timeScale = 0;
TogglePauseMenu(true); TogglePauseMenu(true);
} else { }
else
{
Time.timeScale = 1; Time.timeScale = 1;
TogglePauseMenu(false); TogglePauseMenu(false);
} }
@ -127,17 +159,20 @@ public class StateController : MonoBehaviour {
} }
} }
public void Unpause() { public void Unpause()
{
Time.timeScale = 1; Time.timeScale = 1;
TogglePauseMenu(false); TogglePauseMenu(false);
isPaused = !isPaused; isPaused = !isPaused;
} }
void TogglePauseMenu(bool showPauseMenu) { void TogglePauseMenu(bool showPauseMenu)
{
pauseMenuCanvas.SetActive(showPauseMenu); pauseMenuCanvas.SetActive(showPauseMenu);
} }
public void RespawnPlayer() { public void RespawnPlayer()
{
Destroy(GameObject.FindGameObjectWithTag("Player")); Destroy(GameObject.FindGameObjectWithTag("Player"));
SetDeathCanvasActive(false); SetDeathCanvasActive(false);
GameObject.Find("Main Camera").GetComponent<CameraMovement>().FindPlayer(); GameObject.Find("Main Camera").GetComponent<CameraMovement>().FindPlayer();
@ -145,21 +180,26 @@ public class StateController : MonoBehaviour {
Instantiate(player, spawnPoint.transform.position, player.transform.rotation); Instantiate(player, spawnPoint.transform.position, player.transform.rotation);
} }
public void RespawnEnemies() { public void RespawnEnemies()
foreach (GameObject enemy in enemiesInScene) { {
foreach (GameObject enemy in enemiesInScene)
{
enemy.SetActive(true); enemy.SetActive(true);
} }
} }
public void SetDeathCanvasActive(bool activeState) { public void SetDeathCanvasActive(bool activeState)
{
deathCanvas.SetActive(activeState); deathCanvas.SetActive(activeState);
} }
public void ShowVictoryCanvas() { public void ShowVictoryCanvas()
{
victoryCanvas.SetActive(true); victoryCanvas.SetActive(true);
} }
public void ContinueToNextLevel() { public void ContinueToNextLevel()
GameObject.FindGameObjectWithTag("SceneManager").GetComponent<SceneController>().NextScene(); {
SceneController.Instance.NextScene();
} }
} }

View File

@ -8,7 +8,8 @@ public class VictoryObjectBehavior : MonoBehaviour
public float speed = 1f; public float speed = 1f;
Vector2 initPosition; Vector2 initPosition;
void Awake() { void Awake()
{
initPosition = this.transform.position; initPosition = this.transform.position;
} }
@ -18,13 +19,16 @@ public class VictoryObjectBehavior : MonoBehaviour
transform.position = new Vector2(initPosition.x, initPosition.y + Mathf.Sin(Time.time * speed) * height); transform.position = new Vector2(initPosition.x, initPosition.y + Mathf.Sin(Time.time * speed) * height);
} }
void OnDrawGizmos() { void OnDrawGizmos()
{
Gizmos.DrawLine(new Vector3(transform.position.x, transform.position.y - height, transform.position.z), new Vector3(transform.position.x, transform.position.y + height, transform.position.z)); Gizmos.DrawLine(new Vector3(transform.position.x, transform.position.y - height, transform.position.z), new Vector3(transform.position.x, transform.position.y + height, transform.position.z));
} }
void OnTriggerEnter2D(Collider2D col) { void OnTriggerEnter2D(Collider2D col)
if (col.tag == "Player") { {
GameObject.FindGameObjectWithTag("StateController").GetComponent<StateController>().ShowVictoryCanvas(); if (col.tag == "Player")
{
StateController.Instance.ShowVictoryCanvas();
} }
} }
} }