Files
Sokoban/Assets/Scripts/Objects/Crate.cs
2023-06-16 09:51:16 +03:00

56 lines
1.4 KiB
C#

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Level;
using DG.Tweening;
namespace Objects
{
public class Crate : MonoBehaviour
{
public Vector2Int layoutPosition; // Index in layout
private void Start()
{
LevelBuilder.Instance.LevelDestroyed += Destroy;
}
private void OnDestroy()
{
LevelBuilder.Instance.LevelDestroyed -= Destroy;
}
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;
currentCell.crate = null;
// Occupy new cell
targetCell.cellData.cellContent = LayoutCell.LayoutCellData.CellContent.Crate;
targetCell.crate = this;
// Update position
layoutPosition = layoutPosition + direction;
// Move object
transform.DOMove(targetCell.worldPos, 1f);
}
}
private void Destroy()
{
Destroy(gameObject);
}
}
}