using System.Collections; using System.Collections.Generic; using UnityEngine; using Level; using DG.Tweening; namespace Objects { public class Player : MonoBehaviour { private static Player instance; public Vector2Int layoutPosition; private bool isMoving = false; public static Player Instance => instance; public bool CanMove { get { return !isMoving && GameManager.Instance.currentState == GameState.Gameplay; } } private void Awake() { if (instance != null && instance != this) { Destroy(gameObject); return; } instance = this; } private void Start() { LevelBuilder.Instance.LevelInitialized += OnLevelInitialized; LevelBuilder.Instance.LevelDestroyed += OnLevelDestroy; } private void Update() { if (CanMove) { if (Input.GetKeyDown(KeyCode.DownArrow)) { Move(Vector2Int.down); } else if (Input.GetKeyDown(KeyCode.UpArrow)) { Move(Vector2Int.up); } else if (Input.GetKeyDown(KeyCode.LeftArrow)) { Move(Vector2Int.left); } else if (Input.GetKeyDown(KeyCode.RightArrow)) { Move(Vector2Int.right); } } } public void Teleport(LayoutCell targetCell, bool clearOldCell=true) { LayoutCell currentCell = LevelBuilder.Instance.GetCellAtLayout(layoutPosition); if (clearOldCell) { // Free previous cell currentCell.cellData.cellContent = LayoutCell.LayoutCellData.CellContent.None; } // Occupy new cell targetCell.cellData.cellContent = LayoutCell.LayoutCellData.CellContent.Player; // Update position layoutPosition = targetCell.layoutPosition; transform.position = targetCell.worldPos; } public void Move(Vector2Int direction) { LayoutCell currentCell = LevelBuilder.Instance.GetCellAtLayout(layoutPosition); LayoutCell targetCell = LevelBuilder.Instance.GetCellAtLayout(layoutPosition + direction); if (targetCell != null && targetCell.IsFree) { // Free previous cell currentCell.cellData.cellContent = LayoutCell.LayoutCellData.CellContent.None; // Occupy new cell targetCell.cellData.cellContent = LayoutCell.LayoutCellData.CellContent.Player; // Update position layoutPosition = layoutPosition + direction; // Move object isMoving = true; transform.DOMove(targetCell.worldPos, 1f).OnComplete(() => isMoving = false); } else if (targetCell != null && targetCell.cellData.cellContent == LayoutCell.LayoutCellData.CellContent.Crate) { targetCell.crate.Move(direction); } } private void OnLevelInitialized() { gameObject.SetActive(true); Teleport(LevelBuilder.Instance.GetCellAtLayout(new Vector2Int(0, 0)), false); } private void OnLevelDestroy() { gameObject.SetActive(false); } } }