BasicFantasy/Assets/Scripts/BlockController.cs
2023-09-28 18:21:45 +09:00

137 lines
3.9 KiB
C#

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class BlockController : MonoBehaviour
{
//block for instantiate
[SerializeField] private GameObject _characterBlock;
[SerializeField] private GameObject _bgBlock;
[SerializeField] private RectTransform _bgRoot;
[SerializeField] private RectTransform _characterRoot;
public E_TEAM CurrentTurn { get; private set; } = E_TEAM.BLUE;
private BackgroundBlock[,] _mapPositions;
private CharacterBlock _selectedCharacter;
private Vector2 _blockSize;
public Vector2 BlockSize
{
get
{
return _blockSize;
}
}
public CharacterBlock GenerateCharacter(CharacterInfo info,int x, int y)
{
info.UpdatePosition(x, y);
var obj = Instantiate(_characterBlock, transform);
var block = obj.GetComponent<CharacterBlock>();
block.SetData(info, _blockSize);
block.UpdatePosition(_mapPositions[x, y].transform.position, x, y);
return block;
}
public void Selected(CharacterBlock block)
{
if(block.Team != CurrentTurn)
{
return;
}
//이미 칠해진 범위 컬러를 초기화
ResetBackground();
//현재 선택된 캐릭터와 같으면 현재 캐릭터 없애줌
if(_selectedCharacter == block)
{
_selectedCharacter = null;
return;
}
else
{
_selectedCharacter = block;
}
SetBackground(block.CurrentX, block.CurrentY, block.Range);
}
public void Move(int x, int y)
{
CurrentTurn = CurrentTurn == E_TEAM.BLUE ? E_TEAM.RED : E_TEAM.BLUE;
//배경 블럭 받아옴
//현재 선택된 캐릭터를 해당 좌표로 이동시키고
ResetBackground();
//모든 칠해진 배경 컬러 초기화
_selectedCharacter.UpdatePosition(_mapPositions[x, y].transform.position, x, y);
}
public void GenerateMap(int x, int y, float padding)
{
_mapPositions = new BackgroundBlock[x, y];
float width = _bgRoot.rect.width - (padding * (x - 1));
float height = _bgRoot.rect.height - (padding * (y - 1));
_blockSize = new Vector2(width / x, height / y);
float xPos = 0;
float yPos = 0;
for (int i = 0; i < y; i++)
{
for (int j = 0; j < x; j++)
{
GameObject obj = Instantiate(_bgBlock, _bgRoot.transform);
var block = obj.GetComponent<BackgroundBlock>();
block.SetData(j, i);
block.SetSize(_blockSize);
block.UpdatePosition(new Vector2(xPos, yPos));
_mapPositions[j, i] = block;
xPos += _blockSize.x + padding;
}
yPos += _blockSize.y + padding;
xPos = 0;
}
}
private void ResetBackground()
{
for (int i = 0; i < _mapPositions.GetLength(0); i++)
{
for (int j = 0; j < _mapPositions.GetLength(1); j++)
{
if(_mapPositions[i, j].InRage)
{
_mapPositions[i, j].ResetColor();
}
}
}
}
private void SetBackground(int x, int y, int range)
{
//범위 안에 있으면 컬러 변경
for(int i = -range; i <= range; i++)
{
for (int j = -range; j <= range; j++)
{
//절대값의 합이 range인 경우?
int dx = i < 0 ? i * -1 : i;
int dy = j < 0 ? j * -1 : j;
if((dx + dy) <= range)
{
if(x + i >= 0 && x + i < _mapPositions.GetLength(0) &&
y + j >= 0 && y + j < _mapPositions.GetLength(1))
{
_mapPositions[x + i, y + j].SetColor(CurrentTurn);
}
}
}
}
}
}