From 53d32ee944517124de95bac6f2cb0f0d87bc7a14 Mon Sep 17 00:00:00 2001 From: gODealOAple Date: Fri, 24 May 2024 06:37:46 +0500 Subject: [PATCH] review --- GoToLift.cs | 19 ++++ Scripts/CameraController.cs | 21 ++-- Scripts/CameraFollow.cs | 26 +++++ Scripts/CameraMovement.cs | 25 +++++ Scripts/CharacterAnimations.cs | 21 ++++ Scripts/CharacterMovement.cs | 44 ++++++++ Scripts/Fear.cs | 36 ++++++ Scripts/FlashSW.cs | 4 +- Scripts/GooseT.cs | 188 ++++++++++++++++++++++++++++++++ Scripts/LevelTransition.cs | 18 +++ Scripts/LiftButtonTrigger.cs | 59 ++++++++++ Scripts/LiftController.cs | 31 ++++-- Scripts/OldLiftButtonTrigger.cs | 57 ++++++++++ Scripts/OpenLift.cs | 22 ++++ Scripts/Player.cs | 76 ++++++++++--- Scripts/Rail trigger 0.cs | 79 ++++++++++++++ Scripts/Rail trigger 1.cs | 77 +++++++++++++ Scripts/Rail trigger 2.cs | 76 +++++++++++++ Scripts/WST.cs | 60 ++++++++++ Scripts/WinTrigger.cs | 67 ++++++++++++ 20 files changed, 973 insertions(+), 33 deletions(-) create mode 100644 GoToLift.cs create mode 100644 Scripts/CameraFollow.cs create mode 100644 Scripts/CameraMovement.cs create mode 100644 Scripts/CharacterAnimations.cs create mode 100644 Scripts/CharacterMovement.cs create mode 100644 Scripts/Fear.cs create mode 100644 Scripts/GooseT.cs create mode 100644 Scripts/LevelTransition.cs create mode 100644 Scripts/LiftButtonTrigger.cs create mode 100644 Scripts/OldLiftButtonTrigger.cs create mode 100644 Scripts/OpenLift.cs create mode 100644 Scripts/Rail trigger 0.cs create mode 100644 Scripts/Rail trigger 1.cs create mode 100644 Scripts/Rail trigger 2.cs create mode 100644 Scripts/WST.cs create mode 100644 Scripts/WinTrigger.cs diff --git a/GoToLift.cs b/GoToLift.cs new file mode 100644 index 0000000..247b692 --- /dev/null +++ b/GoToLift.cs @@ -0,0 +1,19 @@ +using System.Collections; +using System.Collections.Generic; +using UnityEngine; + +// review(24.05.2024): кажется, что этот класс ничего не делает. Стоит его удалить, чтобы не мешался +public class GoToLift : MonoBehaviour +{ + // Start is called before the first frame update + void Start() + { + + } + + // Update is called once per frame + void Update() + { + + } +} diff --git a/Scripts/CameraController.cs b/Scripts/CameraController.cs index 076e03b..aa4f32b 100644 --- a/Scripts/CameraController.cs +++ b/Scripts/CameraController.cs @@ -6,7 +6,8 @@ public class CameraController : MonoBehaviour { - private float dumping = 1.5f; + public static int sharedValue = 0; + private float dumping = 4f; private Vector2 offset = new (2f, 1f); private bool isLeft; @@ -22,14 +23,13 @@ public class CameraController : MonoBehaviour [SerializeField] private float upperLimit; - // Start is called before the first frame update - void Start() + private void Start() { offset = new Vector2(Math.Abs(offset.x), offset.y); FindPlayer(isLeft); } - public void FindPlayer(bool playerIsLeft) + private void FindPlayer(bool playerIsLeft) { player = GameObject.FindGameObjectsWithTag("Player").First().transform; lastX = Mathf.RoundToInt(player.position.x); @@ -45,10 +45,9 @@ public void FindPlayer(bool playerIsLeft) } } - // Update is called once per frame - void Update() + private void Update() { - if (player) + if (player) // review(24.05.2024): Непонятно, как Transform преобразуется в bool { var currentX = Mathf.RoundToInt(player.position.x); if (currentX > lastX) @@ -57,6 +56,7 @@ void Update() isLeft = true; lastX = Mathf.RoundToInt(player.position.x); + // review(24.05.2024): тернарником бы лаконичнее смотерлось Vector3 target; if (isLeft) { @@ -80,5 +80,12 @@ void Update() Mathf.Clamp(transform.position.y, bottomLimit, upperLimit), transform.position.z ); + if (sharedValue == 1) { + var camTransform = GetComponent(); + var originPos = camTransform.localPosition; + float shakeDur = 1f, shakeAmount = 0.1f, decreaseFact = 1.5f; + + camTransform.localPosition = originPos + UnityEngine.Random.insideUnitSphere * shakeAmount; + } } } diff --git a/Scripts/CameraFollow.cs b/Scripts/CameraFollow.cs new file mode 100644 index 0000000..29bb79d --- /dev/null +++ b/Scripts/CameraFollow.cs @@ -0,0 +1,26 @@ +using UnityEngine; + +public class CameraFollow : MonoBehaviour +{ + public static int sharedValue = 0; + public Transform target; + public float smoothSpeed = 0.125f; + public Vector3 offset; + + void FixedUpdate() + { + if (target != null) + { + var desiredPosition = target.position + offset; + var smoothedPosition = Vector3.Lerp(transform.position, desiredPosition, smoothSpeed); + transform.position = smoothedPosition; + + transform.position = new Vector3( + Mathf.Clamp(transform.position.x, -13.7f, 6.95f), + Mathf.Clamp(transform.position.y, -10, 10), + transform.position.z + ); + } + + } +} \ No newline at end of file diff --git a/Scripts/CameraMovement.cs b/Scripts/CameraMovement.cs new file mode 100644 index 0000000..385a2b3 --- /dev/null +++ b/Scripts/CameraMovement.cs @@ -0,0 +1,25 @@ +using UnityEngine; + +public class CameraMovement : MonoBehaviour +{ + public Transform target; + public float smoothSpeed = 0.125f; + public Vector3 offset; + + void FixedUpdate() + { + if (target != null) + { + var desiredPosition = target.position + offset; + var smoothedPosition = Vector3.Lerp(transform.position, desiredPosition, smoothSpeed); + transform.position = smoothedPosition; + + // review(24.05.2024): Мне тут райдер советует выделить переменную var position = transform.position, ее поменять и присвоить transform.position = position; + transform.position = new Vector3( + Mathf.Clamp(transform.position.x, -13.7f, 6.95f), + Mathf.Clamp(transform.position.y, -10, 10), + transform.position.z + ); + } + } +} \ No newline at end of file diff --git a/Scripts/CharacterAnimations.cs b/Scripts/CharacterAnimations.cs new file mode 100644 index 0000000..8699935 --- /dev/null +++ b/Scripts/CharacterAnimations.cs @@ -0,0 +1,21 @@ +using System.Collections; +using System.Collections.Generic; +using UnityEngine; + +public class CharacterAnimations : MonoBehaviour +{ + private Animator animator; + public bool IsWalking { private get; set; } + public bool IsRunning { private get; set; } + + private void Start() + { + animator = GetComponent(); + } + + private void FixedUpdate() + { + animator.SetBool("isWalking", IsWalking); + animator.SetBool("isRunning", IsRunning); + } +} diff --git a/Scripts/CharacterMovement.cs b/Scripts/CharacterMovement.cs new file mode 100644 index 0000000..177ceb8 --- /dev/null +++ b/Scripts/CharacterMovement.cs @@ -0,0 +1,44 @@ +using System.Collections; +using System.Collections.Generic; +using UnityEngine; + +public class CharacterMovement : MonoBehaviour +{ + [SerializeField] private float speed; + private Vector3 input; + private bool isWalking; + private bool isRunning; + private Animator animator; + private CharacterAnimations animations; + [SerializeField] private SpriteRenderer characterSprite; + + private void Start() + { + animator = GetComponent(); + animations = GetComponentInChildren(); + } + + private void FixedUpdate() => Move(); + + // review(24.05.2024): Я уже видел этот код в PlayerController + private void Move() + { + input = new Vector2(Input.GetAxis("Horizontal"), 0); + isWalking = input.x != 0; + isRunning = input.x != 0 && (Input.GetKey(KeyCode.LeftShift) || Input.GetKey(KeyCode.RightShift)); + + if (isWalking || isRunning) + { + var animationToPlay = isRunning ? "Run" : "Walk"; + var movementSpeed = isRunning ? 3f * speed : speed; + animator.Play(animationToPlay); + characterSprite.flipX = input.x > 0; + transform.position += input * (movementSpeed * Time.deltaTime); + } + else + animator.Play("Calm"); + + animations.IsWalking = isWalking; + animations.IsRunning = isRunning; + } +} \ No newline at end of file diff --git a/Scripts/Fear.cs b/Scripts/Fear.cs new file mode 100644 index 0000000..ce3c462 --- /dev/null +++ b/Scripts/Fear.cs @@ -0,0 +1,36 @@ +using System.Collections; +using System.Collections.Generic; +using UnityEngine; + +public class Fear : MonoBehaviour +{ + // review(24.05.2024): Публичное статическое изменяемое поле, хм... Можем ли мы хотя бы методами его закрыть? + // review(24.05.2024): Ну и название непонятноеы + public static int sharedValue = 0; + public int saved = 0; // review(24.05.2024): Почему оно публичное? Может, это previousFear? + // Start is called before the first frame update + void Start() + { + + } + + // Update is called once per frame + void Update() + { + if (saved != sharedValue) + { + saved = sharedValue; + if (sharedValue == 1) + { + //Camera.main.gameObject.AddComponent(); + GetComponent().Play(); + CameraController.sharedValue = 1; // review(24.05.2024): Может, лучше в CameraController обращаться к Fear.sharedValue, чтобы был только один источник правды? + } + else if (sharedValue == 0) { + GetComponent().Pause(); + CameraController.sharedValue = 0; + } + } + + } +} diff --git a/Scripts/FlashSW.cs b/Scripts/FlashSW.cs index 40b7da3..b1c7723 100644 --- a/Scripts/FlashSW.cs +++ b/Scripts/FlashSW.cs @@ -2,6 +2,7 @@ using System.Collections.Generic; using UnityEngine; +// review(24.05.2024): Дайте полям нормальные названия public class FlashSW : MonoBehaviour { @@ -17,7 +18,8 @@ void Start() // Update is called once per frame void Update() { - if (Input.GetKeyUp(FLC)){ + if (Input.GetKeyUp(FLC)) + { FL.enabled = ! FL.enabled; GetComponent().PlayOneShot(FLS); } diff --git a/Scripts/GooseT.cs b/Scripts/GooseT.cs new file mode 100644 index 0000000..406c6a7 --- /dev/null +++ b/Scripts/GooseT.cs @@ -0,0 +1,188 @@ +using System.Collections; +using System.Collections.Generic; +using UnityEngine; +using UnityEngine.SceneManagement; +using UnityEngine.Serialization; +using UnityEngine.UI; + +// review(24.05.2024): Непонятное имя и переменные +public class GooseT : MonoBehaviour +{ + [FormerlySerializedAs("k")] public int meetingCount = 0; + public GameObject balance; + public GameObject feather; + public GameObject ticket; + public GameObject dkr; + public GameObject money; + public GameObject wool; + public Image dkrV; + public Image ticketV; + public Image imageComponent; + + public float timeToCount = 5f; // Время таймера в секундах + private bool isCounting = false; + + // Новое изображение для замены + public Sprite Big; + public Sprite SVD; + + public bool d = false; + public bool t = false; + + // Метод для замены изображения + public void ChangeSourceImage(int t) + { + if (t == 1) + { + imageComponent.sprite = Big; + money.SetActive(true); + } + + if (t == 3) + { + imageComponent.sprite = SVD; + wool.SetActive(true); + meetingCount += 1; + } + + } + + // Start is called before the first frame update + void Start() + { + + } + + // Update is called once per frame + void Update() + { + if (PlayerController.dkr == 1) + { + PlayerController.dkr = 0; + dkrV.enabled = true; + d = true; + StartCoroutine(FadeInD()); + GetComponent().Play(); + } + if (PlayerController.ticket == 1) + { + PlayerController.ticket = 0; + ticketV.enabled = true; + t = true; + StartCoroutine(FadeInT()); + GetComponent().Play(); + } + } + + IEnumerator FadeInD() + { + dkrV.color = new Color(dkrV.color.r, dkrV.color.g, dkrV.color.b, 0); + + while (dkrV.color.a < 1) + { + dkrV.color = new Color(dkrV.color.r, dkrV.color.g, dkrV.color.b, dkrV.color.a + Time.deltaTime); + yield return null; + } + + yield return new WaitForSeconds(1); // Ждем 2 секунды + + StartCoroutine(FadeOutD()); + } + + IEnumerator FadeOutD() + { + while (dkrV.color.a > 0) + { + dkrV.color = new Color(dkrV.color.r, dkrV.color.g, dkrV.color.b, dkrV.color.a - Time.deltaTime); + yield return null; + } + + dkrV.enabled = false; + dkr.SetActive(true); + } + + IEnumerator FadeInT() + { + // review(24.05.2024): Я уже видел этот код. Давайте избавимся от дублирования + ticketV.color = new Color(ticketV.color.r, ticketV.color.g, ticketV.color.b, 0); + + while (ticketV.color.a < 1) + { + ticketV.color = new Color(ticketV.color.r, ticketV.color.g, ticketV.color.b, ticketV.color.a + Time.deltaTime); + yield return null; + } + + yield return new WaitForSeconds(1); // Ждем 2 секунды + + StartCoroutine(FadeOutT()); + } + + IEnumerator FadeOutT() + { + while (ticketV.color.a > 0) + { + ticketV.color = new Color(ticketV.color.r, ticketV.color.g, ticketV.color.b, ticketV.color.a - Time.deltaTime); + yield return null; + } + + ticketV.enabled = false; + ticket.SetActive(true); + } + + private void OnTriggerEnter2D(Collider2D other) + { + if (meetingCount == 4) + { + wool.SetActive(false); + feather.SetActive(true); + GetComponent().Play(); + meetingCount += 1; + } + + if (meetingCount == 2 && d) + { + d = false; + dkr.SetActive(false); + GetComponent().Play(); + meetingCount += 1; + } + + if (meetingCount == 1) + { + money.SetActive(false); + balance.SetActive(true); + GetComponent().Play(); + StartCoroutine(StartTimer()); + meetingCount += 1; + } + + if (meetingCount == 0 && t) + { + t = false; + ticket.SetActive(false); + GetComponent().Play(); + meetingCount += 1; + } + } + + private void OnTriggerExit2D(Collider2D other) + { + if (other.CompareTag("Player")) + { + ChangeSourceImage(meetingCount); + } + } + + IEnumerator StartTimer() + { + isCounting = true; // Устанавливаем флаг, что таймер запущен + while (timeToCount > 0) // Пока время не истечет + { + yield return new WaitForSeconds(1f); // Ждем одну секунду + timeToCount -= 1f; // Уменьшаем время на одну секунду + Debug.Log(timeToCount); // Выводим оставшееся время в консоль + } + isCounting = false; // Таймер закончился, сбрасываем флаг + balance.SetActive(false); // Сообщаем, что время истекло + } +} diff --git a/Scripts/LevelTransition.cs b/Scripts/LevelTransition.cs new file mode 100644 index 0000000..654886f --- /dev/null +++ b/Scripts/LevelTransition.cs @@ -0,0 +1,18 @@ +using System.Collections; +using System.Collections.Generic; +using UnityEngine; + +public class LevelTransition : MonoBehaviour +{ + // Start is called before the first frame update + void Start() + { + + } + + // Update is called once per frame + void Update() + { + + } +} diff --git a/Scripts/LiftButtonTrigger.cs b/Scripts/LiftButtonTrigger.cs new file mode 100644 index 0000000..ea8a8b2 --- /dev/null +++ b/Scripts/LiftButtonTrigger.cs @@ -0,0 +1,59 @@ +using System; +using System.Collections; +using System.Collections.Generic; +using UnityEngine; +using UnityEngine.SceneManagement; + +public class LiftButtonTrig : MonoBehaviour +{ + public GameObject otherObject; // ссылка на другой объект + + private Animator otherObjectAnimator; // компонент аниматора другого объекта + + private Animator animator; + + [SerializeField] + public float timeToCount; // Время таймера в секундах + private bool isCounting; // Флаг, показывающий, запущен ли таймер + private bool startLoadScene; + + + void Start() + { + // Получаем компонент аниматора другого объекта + otherObjectAnimator = otherObject.GetComponent(); + } + + IEnumerator StartTimer() + { + isCounting = true; // Устанавливаем флаг, что таймер запущен + while (timeToCount > 0) // Пока время не истечет + { + yield return new WaitForSeconds(1f); // Ждем одну секунду + timeToCount -= 1f; // Уменьшаем время на одну секунду + Debug.Log(timeToCount); // Выводим оставшееся время в консоль + } + isCounting = false; // Таймер закончился, сбрасываем флаг + SceneManager.LoadScene("Lift"); // Сообщаем, что время истекло + } + + private void OnTriggerEnter2D(Collider2D other) + { + startLoadScene = other.CompareTag("Player"); + } + + private void OnTriggerExit2D(Collider2D other) + { + startLoadScene = false; + } + + private void Update() + { + if (startLoadScene && Input.GetKey(KeyCode.E)) + { + otherObjectAnimator.SetBool("IsSwitchOn", true); + GetComponent().Play(); + StartCoroutine(StartTimer()); + } + } +} diff --git a/Scripts/LiftController.cs b/Scripts/LiftController.cs index 4b62677..426684a 100644 --- a/Scripts/LiftController.cs +++ b/Scripts/LiftController.cs @@ -1,22 +1,35 @@ -using System.Collections; +using System.Collections; using System.Collections.Generic; using UnityEngine; +using UnityEngine.SceneManagement; public class LiftController : MonoBehaviour { - public Animator Animator; - // Start is called before the first frame update + private Animator animator; + public float timeToCount = 4f; // Время таймера в секундах + private bool isCounting = false; // Флаг, показывающий, запущен ли таймер + + IEnumerator StartTimer() + { + // review(24.05.2024): Код очень часто дублируется + isCounting = true; // Устанавливаем флаг, что таймер запущен + while (timeToCount > 0) // Пока время не истечет + { + yield return new WaitForSeconds(1f); // Ждем одну секунду + timeToCount -= 1f; // Уменьшаем время на одну секунду + Debug.Log(timeToCount); // Выводим оставшееся время в консоль + } + isCounting = false; // Таймер закончился, сбрасываем флаг + SceneManager.LoadScene("Dungeon"); // Сообщаем, что время истекло + } + private void Start() { - Animator = GetComponent(); + animator = GetComponent(); + StartCoroutine(StartTimer()); } - // Update is called once per frame private void Update() { - if (Input.GetKey(KeyCode.E)) - { - Animator.SetBool("IsSwitchOn", true); - } } } diff --git a/Scripts/OldLiftButtonTrigger.cs b/Scripts/OldLiftButtonTrigger.cs new file mode 100644 index 0000000..dddef27 --- /dev/null +++ b/Scripts/OldLiftButtonTrigger.cs @@ -0,0 +1,57 @@ +using System.Collections; +using UnityEngine; +using UnityEngine.SceneManagement; + +public class OldLiftButtonTrigger : MonoBehaviour +{ + public GameObject otherObject; // ссылка на другой объект + + private Animator otherObjectAnimator; // компонент аниматора другого объекта + + private Animator animator; + + [SerializeField] + public float timeToCount; // Время таймера в секундах + private bool isCounting; // Флаг, показывающий, запущен ли таймер + private bool startLoadScene; + + + void Start() + { + // Получаем компонент аниматора другого объекта + otherObjectAnimator = otherObject.GetComponent(); + } + + IEnumerator StartTimer() + { + isCounting = true; // Устанавливаем флаг, что таймер запущен + while (timeToCount > 0) // Пока время не истечет + { + yield return new WaitForSeconds(1f); // Ждем одну секунду + timeToCount -= 1f; // Уменьшаем время на одну секунду + Debug.Log(timeToCount); // Выводим оставшееся время в консоль + } + isCounting = false; // Таймер закончился, сбрасываем флаг + SceneManager.LoadScene("Plotinka"); // Сообщаем, что время истекло + } + + private void OnTriggerEnter2D(Collider2D other) + { + startLoadScene = other.CompareTag("Player"); + } + + private void OnTriggerExit2D(Collider2D other) + { + startLoadScene = false; + } + + private void Update() + { + if (startLoadScene && Input.GetKey(KeyCode.E)) + { + otherObjectAnimator.SetBool("IsSwitchOn", true); + GetComponent().Play(); + StartCoroutine(StartTimer()); + } + } +} diff --git a/Scripts/OpenLift.cs b/Scripts/OpenLift.cs new file mode 100644 index 0000000..22f3ca2 --- /dev/null +++ b/Scripts/OpenLift.cs @@ -0,0 +1,22 @@ +using System.Collections; +using System.Collections.Generic; +using UnityEngine; + +public class OpenLift : MonoBehaviour +{ + private Animator animator; + + private void Start() + { + animator = GetComponent(); + } + + private void Update() + { + if (Input.GetKey(KeyCode.E)) + { + animator.SetBool("IsSwitchOn", true); + } + } + +} diff --git a/Scripts/Player.cs b/Scripts/Player.cs index 14600b0..89b1fec 100644 --- a/Scripts/Player.cs +++ b/Scripts/Player.cs @@ -1,36 +1,79 @@ using UnityEngine; +using System.Collections; +using UnityEngine.Serialization; +// review(24.05.2024): Название класса не соответствует названию файла public class PlayerController : MonoBehaviour { + [SerializeField] private float speed = 15; + private Vector3 input; + private bool isWalking; // review(24.05.2024): Если isWalking, isRunning, isCalm взаимоисключающие состояния, то стоит создать enum PlayerState и использовать его + private bool isRunning; + private CharacterAnimations animations; + [SerializeField] private SpriteRenderer characterSprite; + + public float Speed // review(24.05.2024): Зачем потребовалось делать это свойством? + { + get => speed; + set => speed = value; + } + + private Animator animator; + private bool isRight; + private float timer = 0f; + private float startTime; + private float endTime; + private float elapsedTime; private Rigidbody2D rb; - public float speed = 5; - public Animator Animator; - public bool isRight; + + public static int ticket = 0; + public static int dkr = 0; + private void Start() { - rb = GetComponent(); - Animator = GetComponent(); + animator = GetComponent(); + startTime = Time.realtimeSinceStartup; + rb = new Rigidbody2D(); } + + private void FixedUpdate() => Update(); // review(24.05.2024): Разве в таком случае не будет вызываться Update слишком часто? + // review(24.05.2024): Перемешана бизнес-логика и логика отображения. Давайте попробуем на уровне кода структурировать это private void Update() { - float moveHorizontal = Input.GetAxis("Horizontal"); - Vector2 movement = new Vector2(moveHorizontal, 0); - Animator.SetFloat("moveX", Mathf.Abs(moveHorizontal)); + if (Input.GetKeyDown(KeyCode.T)) + { + ticket = 1; + } - if (Input.GetKey(KeyCode.LeftShift)) + if (Input.GetKeyDown(KeyCode.Y)) { - Animator.SetBool("running", true); - rb.velocity = movement * speed * 2; + dkr = 1; } - else + + float moveHorizontal = Input.GetAxis("Horizontal"); // review(24.05.2024): var + input = new Vector2(moveHorizontal, 0); + animator.SetFloat("moveX", Mathf.Abs(moveHorizontal)); + isWalking = input.x != 0; + isRunning = input.x != 0 && (Input.GetKey(KeyCode.LeftShift) || Input.GetKey(KeyCode.RightShift)); + + if (isWalking || isRunning) { - Animator.SetBool("running", false); - rb.velocity = movement * speed; + var animationToPlay = isRunning ? "Run" : "Walk"; + var movementSpeed = isRunning ? 3f * speed : speed; + animator.Play(animationToPlay); + Reflect(input); + transform.position += input * (movementSpeed * Time.deltaTime); } + else + animator.Play("Calm"); - Reflect(movement); + // review(24.05.2024): Мне кажется, что за страх должен отвечать отдельный MonoBehavior + endTime = Time.realtimeSinceStartup; + elapsedTime = endTime - startTime; + if (elapsedTime >= 10f) + Fear.sharedValue = 1; } private void Reflect(Vector2 movement) @@ -39,7 +82,8 @@ private void Reflect(Vector2 movement) { transform.localScale *= new Vector2(-1, 1); isRight = !isRight; + Fear.sharedValue = 0; + startTime = Time.realtimeSinceStartup; } } - } \ No newline at end of file diff --git a/Scripts/Rail trigger 0.cs b/Scripts/Rail trigger 0.cs new file mode 100644 index 0000000..79bee24 --- /dev/null +++ b/Scripts/Rail trigger 0.cs @@ -0,0 +1,79 @@ +using System; +using System.Collections; +using System.Collections.Generic; +using UnityEngine; +using UnityEngine.SceneManagement; +using UnityEngine; +using UnityEngine.UI; + +// review(24.05.2024): Давайте объединим всю логику RailTrigger в одном компоненте. В них мало что меняется, как я понял +public class RailTrig0 : MonoBehaviour +{ + public GameObject Player; // ссылка на другой объект + + private Animator otherObjectAnimator; // компонент аниматора другого объекта + + private Animator animator; + + public float timeToCount = 2f; // Время таймера в секундах + private bool isCounting = false; // Флаг, показывающий, запущен ли таймер + private bool btns = false; + + void Start() + { + // Получаем компонент аниматора другого объекта + + } + + void Update() + { + if (btns) + { + if (Input.GetKeyDown(KeyCode.E) && false) + { + Player.SetActive(false); + GetComponent().Play(); + StartCoroutine(StartTimer()); + Player.transform.position = new Vector3(1126, 128, -1); + } + if (Input.GetKeyDown(KeyCode.R)) + { + Player.SetActive(false); + GetComponent().Play(); + StartCoroutine(StartTimer()); + Player.transform.position = new Vector3(1126, 29, -1); + } + } + } + + // review(24.05.2024): непонятно, зачем нужен таймер + в данном методе не только таймер стартуеты + IEnumerator StartTimer() + { + isCounting = true; // Устанавливаем флаг, что таймер запущен + while (timeToCount > 0) // Пока время не истечет + { + yield return new WaitForSeconds(1f); // Ждем одну секунду + timeToCount -= 1f; // Уменьшаем время на одну секунду + Debug.Log(timeToCount); // Выводим оставшееся время в консоль + } + isCounting = false; // Таймер закончился, сбрасываем флаг + // Сообщаем, что время истекло + timeToCount = 2f; + Player.SetActive(true); + } + + + + private void OnTriggerEnter2D(Collider2D other) + { + btns = true; + } + + private void OnTriggerExit2D(Collider2D other) + { + // Проверяем, что объект, покидающий триггер, имеет нужный тег + btns = false; + // Здесь можно добавить необходимую логику + } + +} diff --git a/Scripts/Rail trigger 1.cs b/Scripts/Rail trigger 1.cs new file mode 100644 index 0000000..e09ba1c --- /dev/null +++ b/Scripts/Rail trigger 1.cs @@ -0,0 +1,77 @@ +using System; +using System.Collections; +using System.Collections.Generic; +using UnityEngine; +using UnityEngine.SceneManagement; +using UnityEngine; +using UnityEngine.UI; + +public class RailTrig1 : MonoBehaviour +{ + public GameObject Player; // ссылка на другой объект + + private Animator otherObjectAnimator; // компонент аниматора другого объекта + + private Animator animator; + + public float timeToCount = 2f; // Время таймера в секундах + private bool isCounting = false; // Флаг, показывающий, запущен ли таймер + private bool btns = false; + + void Start() + { + // Получаем компонент аниматора другого объекта + + } + + void Update() + { + if (btns) + { + if (Input.GetKeyDown(KeyCode.E)) + { + Player.SetActive(false); + GetComponent().Play(); + StartCoroutine(StartTimer()); + Player.transform.position = new Vector3(1126, 128, -1); + } + if (Input.GetKeyDown(KeyCode.R)) + { + Player.SetActive(false); + GetComponent().Play(); + StartCoroutine(StartTimer()); + Player.transform.position = new Vector3(1126, -74, -1); + } + } + } + + + IEnumerator StartTimer() + { + isCounting = true; // Устанавливаем флаг, что таймер запущен + while (timeToCount > 0) // Пока время не истечет + { + yield return new WaitForSeconds(1f); // Ждем одну секунду + timeToCount -= 1f; // Уменьшаем время на одну секунду + Debug.Log(timeToCount); // Выводим оставшееся время в консоль + } + isCounting = false; // Таймер закончился, сбрасываем флаг + // Сообщаем, что время истекло + timeToCount = 2f; + Player.SetActive(true); + } + + + + private void OnTriggerEnter2D(Collider2D other) + { + btns = true; + } + + private void OnTriggerExit2D(Collider2D other) + { + btns = false; + // Здесь можно добавить необходимую логику + } + +} diff --git a/Scripts/Rail trigger 2.cs b/Scripts/Rail trigger 2.cs new file mode 100644 index 0000000..34acb5b --- /dev/null +++ b/Scripts/Rail trigger 2.cs @@ -0,0 +1,76 @@ +using System; +using System.Collections; +using System.Collections.Generic; +using UnityEngine; +using UnityEngine.SceneManagement; +using UnityEngine; +using UnityEngine.UI; + +public class RailTrig2 : MonoBehaviour +{ + public GameObject Player; // ссылка на другой объект + + private Animator otherObjectAnimator; // компонент аниматора другого объекта + + private Animator animator; + + public float timeToCount = 2f; // Время таймера в секундах + private bool isCounting = false; // Флаг, показывающий, запущен ли таймер + private bool btns = false; + + void Start() + { + // Получаем компонент аниматора другого объекта + + } + + void Update() + { + if (btns) + { + if (Input.GetKeyDown(KeyCode.E)) + { + Player.SetActive(false); + GetComponent().Play(); + StartCoroutine(StartTimer()); + Player.transform.position = new Vector3(1126, 29, -1); + } + if (Input.GetKeyDown(KeyCode.R) && false) + { + Player.SetActive(false); + GetComponent().Play(); + StartCoroutine(StartTimer()); + Player.transform.position = new Vector3(1126, 29, -1); + } + } + } + + + IEnumerator StartTimer() + { + isCounting = true; // Устанавливаем флаг, что таймер запущен + while (timeToCount > 0) // Пока время не истечет + { + yield return new WaitForSeconds(1f); // Ждем одну секунду + timeToCount -= 1f; // Уменьшаем время на одну секунду + Debug.Log(timeToCount); // Выводим оставшееся время в консоль + } + isCounting = false; // Таймер закончился, сбрасываем флаг + // Сообщаем, что время истекло + timeToCount = 2f; + Player.SetActive(true); + } + + + + private void OnTriggerEnter2D(Collider2D other) + { + btns = true; + } + + private void OnTriggerExit2D(Collider2D other) + { + btns = false; + } + +} diff --git a/Scripts/WST.cs b/Scripts/WST.cs new file mode 100644 index 0000000..33c5cf9 --- /dev/null +++ b/Scripts/WST.cs @@ -0,0 +1,60 @@ +using System; +using UnityEngine; +using System.Collections; +using UnityEngine.UI; + +// review(24.05.2024): Непонятное название класса +public class WST : MonoBehaviour +{ + public Image image; + + void Start() + { + image.enabled = false; + } + + void Update() + { + if (Input.GetKeyDown(KeyCode.L)) + { + ShowWastedScreen(); + } + } + + void ShowWastedScreen() + { + image.enabled = true; + StartCoroutine(FadeIn()); + GetComponent().Play(); // review(24.05.2024): Имеет смысл навесить атрибут RequiredComponent и положить компонент в поле класса при создании либо при Awake + } + + IEnumerator FadeIn() + { + image.color = new Color(image.color.r, image.color.g, image.color.b, 0); + + while (image.color.a < 1) + { + // review(24.05.2024): Тут как будто бы не хватает extension method для Color: image.color.WithAlpha(). Код бы стало проще читать кмк + image.color = new Color(image.color.r, image.color.g, image.color.b, image.color.a + Time.deltaTime); + yield return null; + } + + // review(24.05.2024): Показательный пример, почему комментарии в большинстве случаев - зло + yield return new WaitForSeconds(4); // Ждем 2 секунды + + StartCoroutine(FadeOut()); + } + + IEnumerator FadeOut() + { + // review(24.05.2024): Логика дублирует FadeIn. Кажется, что можно выделить общий метод. Плюс к тому, тут никак не ограничивается + // альфа-компонента цвета. Стоит добавить ограничение, чтобы она всегда была от 0 до 255 включительно + while (image.color.a > 0) + { + image.color = new Color(image.color.r, image.color.g, image.color.b, image.color.a - Time.deltaTime); + yield return null; + } + + image.enabled = false; + } +} diff --git a/Scripts/WinTrigger.cs b/Scripts/WinTrigger.cs new file mode 100644 index 0000000..a16b132 --- /dev/null +++ b/Scripts/WinTrigger.cs @@ -0,0 +1,67 @@ +using System; +using System.Collections; +using System.Collections.Generic; +using UnityEngine; +using UnityEngine.SceneManagement; + + +public class WinTrigger : MonoBehaviour +{ + + // review(24.05.2024): Многие комментарии бесполезны + // review(24.05.2024): Публичные и приватные поля вразнобой + public GameObject otherObject; // ссылка на другой объект + + private Animator otherObjectAnimator; // компонент аниматора другого объекта + + private Animator animator; + + private bool triger = true; // review(24.05.2024): trigger + + [SerializeField] + public float timeToCount = 2f; // Время таймера в секундах + private bool isCounting; // Флаг, показывающий, запущен ли таймер + private bool startLoadScene; + + + void Start() + { + // Получаем компонент аниматора другого объекта + otherObjectAnimator = otherObject.GetComponent(); + } + + IEnumerator StartTimer() + { + isCounting = true; // Устанавливаем флаг, что таймер запущен + while (timeToCount > 0) // Пока время не истечет + { + yield return new WaitForSeconds(1f); // Ждем одну секунду + timeToCount -= 1f; // Уменьшаем время на одну секунду + Debug.Log(timeToCount); // Выводим оставшееся время в консоль + } + isCounting = false; // Таймер закончился, сбрасываем флаг + timeToCount = 4f; + SceneManager.LoadScene("Plotinka"); // Сообщаем, что время истекло + } + + private void OnTriggerEnter2D(Collider2D other) + { + startLoadScene = other.CompareTag("Finish"); + } + + private void OnTriggerExit2D(Collider2D other) + { + startLoadScene = false; + } + + private void Update() + { + if (startLoadScene && Input.GetKey(KeyCode.E) && triger) + { + triger = false; + otherObjectAnimator.SetBool("IsSwitchOn", true); + GetComponent().Play(); // review(24.05.2024): Стоит вынести в поле + StartCoroutine(StartTimer()); + } + } +}