98 lines
2.8 KiB
C#
98 lines
2.8 KiB
C#
using System.Collections;
|
|
using System.Collections.Generic;
|
|
using UnityEngine;
|
|
|
|
public class PlayerController : MonoBehaviour
|
|
{
|
|
private MazeGenerator mazeGenerator;
|
|
private MazeNode[,] nodes;
|
|
private Vector2Int currentIndex;
|
|
private float moveCooldown = 0.2f;
|
|
private float lastMoveTime = 0f;
|
|
|
|
private void Start()
|
|
{
|
|
mazeGenerator = FindFirstObjectByType<MazeGenerator>();
|
|
nodes = mazeGenerator.GetNodes();
|
|
|
|
currentIndex = new Vector2Int(0, 0); // Start node
|
|
transform.position = mazeGenerator.GetNodeWorldPosition(currentIndex.x, currentIndex.y);
|
|
}
|
|
|
|
public void InitMaze(MazeGenerator generator)
|
|
{
|
|
this.mazeGenerator = generator;
|
|
this.nodes = generator.GetNodes();
|
|
|
|
currentIndex = new Vector2Int(0, 0);
|
|
transform.position = mazeGenerator.GetNodeWorldPosition(currentIndex.x, currentIndex.y);
|
|
}
|
|
|
|
public void MoveToStart()
|
|
{
|
|
Transform node = GameObject.Find("nodes_0_0")?.transform;
|
|
|
|
if (node != null)
|
|
{
|
|
transform.position = node.position + new Vector3(0, 0, -1);
|
|
}
|
|
}
|
|
|
|
private void Update()
|
|
{
|
|
if (Time.time - lastMoveTime < moveCooldown)
|
|
return;
|
|
|
|
Vector2Int newIndex = currentIndex;
|
|
|
|
if (Input.GetKeyDown(KeyCode.W) && !nodes[currentIndex.x, currentIndex.y].IsWall(MazeNode.Directions.TOP))
|
|
{
|
|
newIndex += Vector2Int.up;
|
|
}
|
|
else if (Input.GetKeyDown(KeyCode.S) && !nodes[currentIndex.x, currentIndex.y].IsWall(MazeNode.Directions.BOTTOM))
|
|
{
|
|
newIndex += Vector2Int.down;
|
|
}
|
|
else if (Input.GetKeyDown(KeyCode.A) && !nodes[currentIndex.x, currentIndex.y].IsWall(MazeNode.Directions.LEFT))
|
|
{
|
|
newIndex += Vector2Int.left;
|
|
}
|
|
else if (Input.GetKeyDown(KeyCode.D) && !nodes[currentIndex.x, currentIndex.y].IsWall(MazeNode.Directions.RIGHT))
|
|
{
|
|
newIndex += Vector2Int.right;
|
|
}
|
|
else
|
|
{
|
|
return;
|
|
}
|
|
|
|
// Cek batas array
|
|
if (newIndex.x < 0 || newIndex.x >= nodes.GetLength(0) || newIndex.y < 0 || newIndex.y >= nodes.GetLength(1))
|
|
return;
|
|
|
|
currentIndex = newIndex;
|
|
transform.position = mazeGenerator.GetNodeWorldPosition(currentIndex.x, currentIndex.y);
|
|
lastMoveTime = Time.time;
|
|
}
|
|
|
|
private void OnTriggerEnter2D(Collider2D other)
|
|
{
|
|
MazeGenerator mazeGen = FindFirstObjectByType<MazeGenerator>();
|
|
|
|
if (other.gameObject == mazeGen.finishNode)
|
|
{
|
|
Debug.Log("FINISH! Level selesai.");
|
|
|
|
LoadNextLevel();
|
|
}
|
|
}
|
|
|
|
void LoadNextLevel()
|
|
{
|
|
UnityEngine.SceneManagement.SceneManager.LoadScene(
|
|
UnityEngine.SceneManagement.SceneManager.GetActiveScene().buildIndex + 1
|
|
);
|
|
}
|
|
|
|
}
|