일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | ||||
4 | 5 | 6 | 7 | 8 | 9 | 10 |
11 | 12 | 13 | 14 | 15 | 16 | 17 |
18 | 19 | 20 | 21 | 22 | 23 | 24 |
25 | 26 | 27 | 28 | 29 | 30 | 31 |
- 유니티
- 게임 독학
- unity
- Unity 독학
- unity 공부
- Unity Chess
- 유니티 독학
- 오픽 im1
- 오픽 im1 5일
- unity 개발
- 크래프톤 정글 게임 랩
- unity 게임 개발
- 게임 개발 독학
- protobuf란
- 유니티 미연시
- ETRI 연구연수
- 유니티 체스
- protobuf 란?
- 유니티 퀘스트
- 유니티 대화
- 게임 개발
- unity 강의
- 크래프톤
- unity 게임
- 유니티 스토리
- 크래프톤 게임 정글 랩
- unity 설치
- 크래프톤 정글랩
- node.js
- 크래프톤 정글 게임랩
- Today
- Total
하참이의 아이디어노트
유니티로 2D 체스 만들기 (6) 본문
https://www.youtube.com/watch?v=vpJ7ykEsTzI&list=PLXV-vjyZiT4b7WGjgiqMy422AVyMaigl1&index=8
글 작성에 앞서 이 주제로 작성한 글들은 전부 위 영상을 참고하여 제작하였음을 밝힙니다.
안녕하십니까? 벌써 유니티로 2D 체스 만들기의 마지막 게시글입니다. 아직 초보자 단계이기도 하고, 유니티의 강점인 3D를 사용하지 않은 점에 지루해하고 계실분들도 있겠지요. 하지만 여기까지 제작하신 분들에게는 분명 게임개발의 기본기를 얻어갔으리라 믿습니다.
이번글에선 체스 게임에서의 턴을 주고받는것과 체크메이트 등을 구현하도록 하겠습니다.
잘부탁드립니다!
우선 게임턴을 다루는 변수와 게임오버를 다루는 변수의 프로퍼티를 다루는 메소드를 만들겠습니다.
스크립트 Game.cs에서 다음과 같은 메소드들을 추가합니다.
public string GetCurrentPlayer()
{
return currentPlayer;
}
public bool IsGameOver()
{
return gameOver;
}
GetCurrentPlayer()은 현재 플레이어를 나타내기위한 string 변수 currentPlayer를 반환합니다.
IsGameOver()은 체크메이트상태(게임종료상태)인지를 나타내기 위한 bool 변수 gameOver를 반환합니다.
그리고 턴을 넘겨주는 메소드와 게임 재시작 기능도 구현해야겠지요. 다음 메소드들도 추가합니다.
public void NextTurn()
{
if (currentPlayer == "white")
{
currentPlayer = "black";
}
else
{
currentPlayer = "white";
}
}
public void Update()
{
if (gameOver == true && Input.GetMouseButtonDown(0))
{
gameOver = false;
SceneManamer.LoadScene("Game");
}
}
NextTurn()은 현재가 백의 차례이면 흑에게, 흑의 차례이면 백에게 넘기는 알고리즘을 구현합니다.
Update() 유니티에서 제공하는 유니티 이벤트 메소드로 프레임이 재생될때마다 호출되는 메소드 입니다. gameOver가 true이고 마우스 좌클릭 상태일때 게임을 재시작합니다.
SceneManager기능을 사용하기 위해 다음과 같이 네임스페이스를 usnig 합니다.
using UnityEngine.SceneManagement;
전부 수정된 Game.cs의 코드는 다음과 같습니다.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
public class Game : MonoBehaviour
{
public GameObject chesspiece;
// Positions and team for each chesspiece
private GameObject[,] positions = new GameObject[8, 8];
private GameObject[] playerBlack = new GameObject[16];
private GameObject[] playerWhite = new GameObject[16];
private string currentPlayer = "white";
private bool gameOver = false;
void Start()
{
playerWhite = new GameObject[] { Create("white_rook", 0, 0), Create("white_knight", 1, 0),
Create("white_bishop", 2, 0), Create("white_queen", 3, 0), Create("white_king", 4, 0),
Create("white_bishop", 5, 0), Create("white_knight", 6, 0), Create("white_rook", 7, 0),
Create("white_pawn", 0, 1), Create("white_pawn", 1, 1), Create("white_pawn", 2, 1),
Create("white_pawn", 3, 1), Create("white_pawn", 4, 1), Create("white_pawn", 5, 1),
Create("white_pawn", 6, 1), Create("white_pawn", 7, 1) };
playerBlack = new GameObject[] { Create("black_rook", 0, 7), Create("black_knight", 1, 7),
Create("black_bishop", 2, 7), Create("black_queen", 3, 7), Create("black_king", 4, 7),
Create("black_bishop", 5, 7), Create("black_knight", 6, 7), Create("black_rook", 7, 7),
Create("black_pawn", 0, 6), Create("black_pawn", 1, 6), Create("black_pawn", 2, 6),
Create("black_pawn", 3, 6), Create("black_pawn", 4, 6), Create("black_pawn", 5, 6),
Create("black_pawn", 6, 6), Create("black_pawn", 7, 6) };
// Set all piece positions on the position board
for (int i = 0; i < playerBlack.Length; i++)
{
SetPosition(playerBlack[i]);
SetPosition(playerWhite[i]);
}
}
public GameObject Create(string name, int x, int y)
{
GameObject obj = Instantiate(chesspiece, new Vector3(0, 0, 1), Quaternion.identity);
Chessman cm = obj.GetComponent<Chessman>();
cm.name = name;
cm.SetXBoard(x);
cm.SetYBoard(y);
cm.Activate();
return obj;
}
public void SetPosition(GameObject obj)
{
Chessman cm = obj.GetComponent<Chessman>();
positions[cm.GetXBoard(), cm.GetYBoard()] = obj;
}
public void SetPositionEmpty(int x, int y)
{
positions[x, y] = null;
}
public GameObject GetPosition(int x, int y)
{
return positions[x, y];
}
public bool PositionOnBoard(int x, int y)
{
if (x < 0 || y < 0 || x >= positions.GetLength(0) || y >= positions.GetLength(1)) return false;
return true;
}
public string GetCurrentPlayer()
{
return currentPlayer;
}
public bool IsGameOver()
{
return gameOver;
}
public void NextTurn()
{
if (currentPlayer == "white")
{
currentPlayer = "black";
}
else
{
currentPlayer = "white";
}
}
public void Update()
{
if (gameOver == true && Input.GetMouseButtonDown(0))
{
gameOver = false;
SceneManager.LoadScene("Game");
}
}
}
다음으로 고 게임 흑백 차례에 맞는 체스 말만 움직일수 있도록 기능을 추가하겠습니다. Chessman.cs 스크립트의 OnMouseUp() 메소드를 다음과 같이 수정합니다.
private void OnMouseUp()
{
if(!controller.GetComponent<Game>().IsGameOver() && controller.GetComponent<Game>().GetCurrentPlayer() == player)
{
DestroyMovePlates();
InitiateMovePlates();
}
}
이제 체스 말이 움직이면 턴을 넘겨주도록 MovePlate.cs의 OnMouseUp() 메소드를 다음과 같이 수정합니다.
public void OnMouseUp()
{
controller = GameObject.FindGameObjectWithTag("GameController");
if (attack)
{
GameObject cp = controller.GetComponent<Game>().GetPosition(matrixX, matrixY);
Destroy(cp);
}
controller.GetComponent<Game>().SetPositionEmpty(reference.GetComponent<Chessman>().GetXBoard(), reference.GetComponent<Chessman>().GetYBoard());
reference.GetComponent<Chessman>().SetXBoard(matrixX);
reference.GetComponent<Chessman>().SetYBoard(matrixY);
reference.GetComponent<Chessman>().SetCoords();
controller.GetComponent<Game>().SetPosition(reference);
controller.GetConponent<Game>().NextTurn();
reference.GetComponent<Chessman>().DestroyMovePlates();
}
controller.GetConponent<Game>().NextTurn(); 부분을 추가하였습니다. moveplate가 클릭되면 체스 말을 움직이고 차례를 상대방에게 넘깁니다.
이제 게임오버(체크메이트)를 만들어보겠습니다. 게임이 끝나면 게임이 끝났다는 사실을 저희는 직관적으로 알아야합니다. 따라서 게임오버 텍스트를 만들어야겠지요. 저희는 그것을 UI로 제작해보겠습니다.
Hierachy 창에서 우클릭을 이용해 UI -> Canvas를 만들어줍니다.
다음으로 Canvas를 바라보는 시점을 카메라를 기준으로 바꾸겠습니다. 간단한 게임 제작 프로젝트이므로 크게 중요한 내용은 아니지만 이후 카메라를 기준으로 UI가 보여진다는 것을 확실히 하기 위해 진행합니다.
Canvas의 Canvas 컴포넌트에서 Render Mode를 Screen Space - Overlay에서 Screen Space - Camera로 변경합니다.
RenderMode를 Screen Space - Camera로 변경하면 하단 Render Mode에 따른 속성들이 변경됩니다. 변경으로 인해 생긴 Render Camera에 Main Camera를 드래그하여 등록합니다.
다음으로 UI Canvas 위에 게임오버(체크메이트) 텍스트를 생성하겠습니다. Hierachy창에서 Canvas 게임 오브젝트를 우클릭, UI -> Text - TextMeshPro를 클릭하여 Text 게임 오브젝트를 생성합니다. (영상에서는 예전 버전을 다루기 때문에 TextMeshPro가 아닌 Text를 사용합니다. 제 글에서는 최신 버전을 사용하는 기준으로 TextMeshPro로 제작하겠습니다만 영상과 같이 만들고 싶으시거나 TextMeshPro를 임포트 하기 귀찮으신 분들 께서는 Legacy의 Text를 사용하셔도 됩니다.
TextMeshPro를 생성하면 다음과 같은 TextMeshPro의 임포터창이 뜨게 됩니다. Import TMP Essentials를 클릭하여 TextMeshPro를 임포트합니다.
다음과 같이 Text의 위치와 크기를 이동시키고 Text 의 Pivot을 일치시킵니다.
Text를 가운데 정렬하기 위하여 Text 컴포넌트의 Alignment속성을 다음과 같이 변경합니다.
처음에는 비어있어야 하기 때문에 다음과 같이 Text 입력칸을 비워둡니다.
Text(TMP)를 복사, 붙여넣기 하여 Text를 하나 더 만듭니다. 복사한 오브젝트는 체스보드 하단으로 이동시킵니다.
하단의 Text에는 Tap To Restart라는 텍스트를 작성해둡니다.
'Unity > Unity Chess' 카테고리의 다른 글
유니티로 2D 체스 만들기 (5) (0) | 2024.03.20 |
---|---|
유니티로 2D 체스 만들기 (4) (0) | 2024.03.18 |
유니티로 2D 체스 만들기 (3) (0) | 2024.03.16 |
유니티로 2D 체스 만들기 (2) (0) | 2024.03.16 |
유니티로 2D 체스 만들기 (1) (0) | 2024.03.16 |