added pathfinding

This commit is contained in:
Janis M
2022-03-09 13:01:02 +01:00
parent a8d8b7b04b
commit 675481d8ad
21 changed files with 962 additions and 311 deletions

View File

@@ -1,35 +0,0 @@
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Area : MonoBehaviour
{
[SerializeField] bool accessable = false;
[SerializeField] GameObject tile;
List<Tile> tiles = new List<Tile>();
int height = 16;
int width = 16;
void Start()
{
GetComponent<SpriteRenderer>().color = Random.ColorHSV(0f, 1f, 1f, 1f, 0.5f, 1f);
//GenerateGrid();
}
void GenerateGrid()
{
for (int x = 0; x < width; x++)
{
for (int y = 0; y < height; y++)
{
GameObject currentTile= Instantiate(tile);
currentTile.transform.position = new Vector3(x - width/2, y-height/2, 1);
//currentTile.transform.SetParent(transform);
tiles.Add(currentTile.GetComponent<Tile>());
}
}
}
}

View File

@@ -5,17 +5,21 @@ using UnityEngine;
// Written with https://www.youtube.com/watch?v=dulosHPl82A
public class GridBuildingSystem : MonoBehaviour
{
public static GridBuildingSystem instance;
[SerializeField] List<PlacedObjectTypeSO> placedObjectTypeSOList = new List<PlacedObjectTypeSO>(); // https://youtu.be/dulosHPl82A?t=1192
PlacedObjectTypeSO placedObjectTypeSO;
Grid<GridObject> grid;
public Grid<GridObject> buildingGrid;
void Awake()
{
if (instance == null)
instance = this;
int gridWidth = 20;
int gridHeight = 20;
float cellSize = 2f;
float cellSize = 1f;
grid = new Grid<GridObject>(gridWidth, gridHeight, cellSize, Vector3.zero, (Grid<GridObject> g, int x, int y) => new GridObject(g, x, y));
buildingGrid = new Grid<GridObject>(gridWidth, gridHeight, cellSize, Vector3.zero, (Grid<GridObject> g, int x, int y) => new GridObject(g, x, y));
placedObjectTypeSO = placedObjectTypeSOList[0];
}
public class GridObject
@@ -40,17 +44,18 @@ public class GridBuildingSystem : MonoBehaviour
}
void Update()
{
if (Input.GetMouseButtonDown(0))
// PLACE
if (Input.GetKeyDown(KeyCode.B))
{
Vector3 mousePosition = new Vector3(Camera.main.ScreenToWorldPoint(Input.mousePosition).x, Camera.main.ScreenToWorldPoint(Input.mousePosition).y);
grid.GetXY(mousePosition, out int x, out int y);
buildingGrid.GetXY(mousePosition, out int x, out int y);
List<Vector2Int> gridPositionList = placedObjectTypeSO.GetGridPositionList(new Vector2Int(x, y), PlacedObjectTypeSO.Dir.Down);
bool canBuild = true;
foreach (Vector2Int gridPosition in gridPositionList)
{
if(!grid.GetGridObject(gridPosition.x, gridPosition.y).CanBuild())
if(!buildingGrid.GetGridObject(gridPosition.x, gridPosition.y).CanBuild())
{
// Cannot build here
canBuild = false;
@@ -60,12 +65,12 @@ public class GridBuildingSystem : MonoBehaviour
if (canBuild)
{
PlacedObject placedObject = PlacedObject.Create(grid.GetWorldPosition(x, y), new Vector2Int(x, y), PlacedObjectTypeSO.Dir.Down, placedObjectTypeSO);
PlacedObject placedObject = PlacedObject.Create(buildingGrid.GetWorldPosition(x, y), new Vector2Int(x, y), PlacedObjectTypeSO.Dir.Down, placedObjectTypeSO);
foreach(Vector2Int gridPosition in gridPositionList)
{
grid.GetGridObject(gridPosition.x, gridPosition.y).SetPlacedObject(placedObject);
buildingGrid.GetGridObject(gridPosition.x, gridPosition.y).SetPlacedObject(placedObject);
}
}
@@ -73,9 +78,10 @@ public class GridBuildingSystem : MonoBehaviour
{
Debug.Log("Cannot build here!" + " " + mousePosition);
}
}else if (Input.GetMouseButtonDown(1))
}else if (Input.GetKeyDown(KeyCode.N)) // DEMOLISH
{
GridObject gridObject = grid.GetGridObject(Camera.main.ScreenToWorldPoint(Input.mousePosition));
GridObject gridObject = buildingGrid.GetGridObject(Camera.main.ScreenToWorldPoint(Input.mousePosition));
PlacedObject placedObject = gridObject.GetPlacedObject();
if (placedObject != null)
{
@@ -85,7 +91,7 @@ public class GridBuildingSystem : MonoBehaviour
foreach (Vector2Int gridPosition in gridPositionList)
{
grid.GetGridObject(gridPosition.x, gridPosition.y).ClearPlacedObject();
buildingGrid.GetGridObject(gridPosition.x, gridPosition.y).ClearPlacedObject();
}
}

View File

@@ -1,6 +1,7 @@
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Tilemaps;
public class PlacedObject : MonoBehaviour
{
@@ -12,6 +13,16 @@ public class PlacedObject : MonoBehaviour
placedObject.placedObjectTypeSO = placedObjectTypeSO;
placedObject.origin = origin;
placedObject.dir = dir;
if (placedObjectTypeSO.isWalkable)
{
foreach(Vector2Int position in placedObject.GetGridPositionList())
{
Pathfinding.Instance.GetNode(position.x, position.y).SetIsWalkable(true);
}
}
return placedObject;
}
@@ -26,6 +37,13 @@ public class PlacedObject : MonoBehaviour
public void DestroySelf()
{
if (placedObjectTypeSO.isWalkable)
{
foreach (Vector2Int position in GetGridPositionList())
{
Pathfinding.Instance.GetNode(position.x, position.y).SetIsWalkable(false);
}
}
Destroy(gameObject);
}
}

View File

@@ -17,7 +17,6 @@ public class PlacedObjectTypeSO : ScriptableObject
case Dir.Right: return Dir.Down;
}
}
public enum Dir
{
Down,
@@ -31,7 +30,7 @@ public class PlacedObjectTypeSO : ScriptableObject
//public Transform visual;
public int width;
public int height;
public bool isWalkable = false;
public int GetRotationAngle(Dir dir)
{

View File

@@ -1,39 +0,0 @@
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class AreaManager : MonoBehaviour
{
[SerializeField] int areaSize = 16;
[SerializeField] int width = 8;
[SerializeField] int height = 8;
[SerializeField] GameObject area;
[SerializeField] List<Area> areas;
private void Start()
{
GenerateGrid();
}
void GenerateGrid()
{
for(int x = 0; x < width; x++)
{
for(int y = 0; y < height; y++)
{
GameObject currentArea = Instantiate(area);
currentArea.transform.position = new Vector3(16*x, 16*y, 1);
areas.Add(currentArea.GetComponent<Area>());
}
}
}
private void OnDrawGizmos()
{
Gizmos.color = Color.blue;
Gizmos.DrawWireCube(Vector3Int.zero, new Vector3Int(areaSize, areaSize, 1));
}
}

View File

@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: edeef0219b3e4e2429e80209bef34286
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,49 @@
/*
------------------- Code Monkey -------------------
Thank you for downloading this package
I hope you find it useful in your projects
If you have any questions let me know
Cheers!
unitycodemonkey.com
--------------------------------------------------
*/
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PathNode {
private Grid<PathNode> grid;
public int x;
public int y;
public int gCost;
public int hCost;
public int fCost;
public bool isWalkable;
public PathNode cameFromNode;
public PathNode(Grid<PathNode> grid, int x, int y) {
this.grid = grid;
this.x = x;
this.y = y;
isWalkable = false;
}
public void CalculateFCost() {
fCost = gCost + hCost;
}
public void SetIsWalkable(bool isWalkable) {
this.isWalkable = isWalkable;
}
public override string ToString() {
return x + "," + y;
}
}

View File

@@ -1,5 +1,5 @@
fileFormatVersion: 2
guid: 5913569e16e68e54584ba0ab5b9ec15a
guid: 8a762ee25504d4344b891ad21350450f
MonoImporter:
externalObjects: {}
serializedVersion: 2

View File

@@ -0,0 +1,161 @@
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Pathfinding {
private const int MOVE_STRAIGHT_COST = 10;
private const int MOVE_DIAGONAL_COST = 14;
public static Pathfinding Instance { get; private set; }
private Grid<PathNode> grid;
private List<PathNode> openList;
private List<PathNode> closedList;
public Pathfinding(int width, int height) {
Instance = this;
grid = new Grid<PathNode>(width, height, 1f, Vector3.zero, (Grid<PathNode> g, int x, int y) => new PathNode(g, x, y));
}
public Grid<PathNode> GetGrid() {
return grid;
}
public List<Vector3> FindPath(Vector3 startWorldPosition, Vector3 endWorldPosition) {
grid.GetXY(startWorldPosition, out int startX, out int startY);
grid.GetXY(endWorldPosition, out int endX, out int endY);
List<PathNode> path = FindPath(startX, startY, endX, endY);
if (path == null) {
return null;
} else {
List<Vector3> vectorPath = new List<Vector3>();
foreach (PathNode pathNode in path) {
vectorPath.Add(new Vector3(pathNode.x, pathNode.y) * grid.GetCellSize() + Vector3.one * grid.GetCellSize() * .5f);
}
return vectorPath;
}
}
public List<PathNode> FindPath(int startX, int startY, int endX, int endY) {
PathNode startNode = grid.GetGridObject(startX, startY);
PathNode endNode = grid.GetGridObject(endX, endY);
if (startNode == null || endNode == null) {
// Invalid Path
return null;
}
openList = new List<PathNode> { startNode };
closedList = new List<PathNode>();
for (int x = 0; x < grid.GetWidth(); x++) {
for (int y = 0; y < grid.GetHeight(); y++) {
PathNode pathNode = grid.GetGridObject(x, y);
pathNode.gCost = 99999999;
pathNode.CalculateFCost();
pathNode.cameFromNode = null;
}
}
startNode.gCost = 0;
startNode.hCost = CalculateDistanceCost(startNode, endNode);
startNode.CalculateFCost();
while (openList.Count > 0) {
PathNode currentNode = GetLowestFCostNode(openList);
if (currentNode == endNode) {
// Reached final node
return CalculatePath(endNode);
}
openList.Remove(currentNode);
closedList.Add(currentNode);
foreach (PathNode neighbourNode in GetNeighbourList(currentNode)) {
if (closedList.Contains(neighbourNode)) continue;
if (!neighbourNode.isWalkable) {
closedList.Add(neighbourNode);
continue;
}
int tentativeGCost = currentNode.gCost + CalculateDistanceCost(currentNode, neighbourNode);
if (tentativeGCost < neighbourNode.gCost) {
neighbourNode.cameFromNode = currentNode;
neighbourNode.gCost = tentativeGCost;
neighbourNode.hCost = CalculateDistanceCost(neighbourNode, endNode);
neighbourNode.CalculateFCost();
if (!openList.Contains(neighbourNode)) {
openList.Add(neighbourNode);
}
}
}
}
// Out of nodes on the openList
return null;
}
private List<PathNode> GetNeighbourList(PathNode currentNode) {
List<PathNode> neighbourList = new List<PathNode>();
if (currentNode.x - 1 >= 0) {
// Left
neighbourList.Add(GetNode(currentNode.x - 1, currentNode.y));
// Left Down
if (currentNode.y - 1 >= 0) neighbourList.Add(GetNode(currentNode.x - 1, currentNode.y - 1));
// Left Up
if (currentNode.y + 1 < grid.GetHeight()) neighbourList.Add(GetNode(currentNode.x - 1, currentNode.y + 1));
}
if (currentNode.x + 1 < grid.GetWidth()) {
// Right
neighbourList.Add(GetNode(currentNode.x + 1, currentNode.y));
// Right Down
if (currentNode.y - 1 >= 0) neighbourList.Add(GetNode(currentNode.x + 1, currentNode.y - 1));
// Right Up
if (currentNode.y + 1 < grid.GetHeight()) neighbourList.Add(GetNode(currentNode.x + 1, currentNode.y + 1));
}
// Down
if (currentNode.y - 1 >= 0) neighbourList.Add(GetNode(currentNode.x, currentNode.y - 1));
// Up
if (currentNode.y + 1 < grid.GetHeight()) neighbourList.Add(GetNode(currentNode.x, currentNode.y + 1));
return neighbourList;
}
public PathNode GetNode(int x, int y) {
return grid.GetGridObject(x, y);
}
private List<PathNode> CalculatePath(PathNode endNode) {
List<PathNode> path = new List<PathNode>();
path.Add(endNode);
PathNode currentNode = endNode;
while (currentNode.cameFromNode != null) {
path.Add(currentNode.cameFromNode);
currentNode = currentNode.cameFromNode;
}
path.Reverse();
return path;
}
private int CalculateDistanceCost(PathNode a, PathNode b) {
int xDistance = Mathf.Abs(a.x - b.x);
int yDistance = Mathf.Abs(a.y - b.y);
int remaining = Mathf.Abs(xDistance - yDistance);
return MOVE_DIAGONAL_COST * Mathf.Min(xDistance, yDistance) + MOVE_STRAIGHT_COST * remaining;
}
private PathNode GetLowestFCostNode(List<PathNode> pathNodeList) {
PathNode lowestFCostNode = pathNodeList[0];
for (int i = 1; i < pathNodeList.Count; i++) {
if (pathNodeList[i].fCost < lowestFCostNode.fCost) {
lowestFCostNode = pathNodeList[i];
}
}
return lowestFCostNode;
}
}

View File

@@ -1,5 +1,5 @@
fileFormatVersion: 2
guid: dc2d10c80076d454fa421658fc397028
guid: e5530caa2a712744aa8742d15eb47ac9
MonoImporter:
externalObjects: {}
serializedVersion: 2

View File

@@ -0,0 +1,46 @@
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Testing : MonoBehaviour {
private Pathfinding pathfinding;
int originX = 0;
int originY = 0;
private void Start() {
pathfinding = new Pathfinding(20, 10);
}
private void Update() {
if (Input.GetMouseButtonDown(0)) {
Vector3 mouseWorldPosition = Camera.main.ScreenToWorldPoint(Input.mousePosition);
pathfinding.GetGrid().GetXY(mouseWorldPosition, out int x, out int y);
List<PathNode> path = pathfinding.FindPath(originX, originY, x, y);
if (path != null) {
float cellSize = pathfinding.GetGrid().GetCellSize();
for (int i=0; i<path.Count - 1; i++) {
Debug.DrawLine(new Vector3(path[i].x, path[i].y) * cellSize + Vector3.one * cellSize/2, new Vector3(path[i+1].x, path[i+1].y) * cellSize + Vector3.one * cellSize/2, Color.green, 5f);
}
}
//characterPathfinding.SetTargetPosition(mouseWorldPosition);
}
if (Input.GetMouseButtonDown(1)) {
Vector3 mouseWorldPosition = Camera.main.ScreenToWorldPoint(Input.mousePosition);
pathfinding.GetGrid().GetXY(mouseWorldPosition, out int x, out int y);
pathfinding.GetNode(x, y).SetIsWalkable(!pathfinding.GetNode(x, y).isWalkable);
originX = x;
originY = y;
}
if (Input.GetMouseButtonDown(2))
{
Vector3 mouseWorldPosition = Camera.main.ScreenToWorldPoint(Input.mousePosition);
pathfinding.GetGrid().GetXY(mouseWorldPosition, out int x, out int y);
pathfinding.GetNode(x, y).SetIsWalkable(!pathfinding.GetNode(x, y).isWalkable);
}
}
}

View File

@@ -1,5 +1,5 @@
fileFormatVersion: 2
guid: 0223944c58fdbb54eb34ad98462c6f27
guid: 4a9e1a4cbcd629e43960027a99f45196
MonoImporter:
externalObjects: {}
serializedVersion: 2

View File

@@ -69,12 +69,13 @@ public class Person : MonoBehaviour
movement = GetComponent<PersonMovement>();
indicators = GetComponent<PersonIndicators>();
TimeManager.OnMinuteUpdate += OnMinuteUpdate;
/* TimeManager.OnMinuteUpdate += OnMinuteUpdate;
TimeManager.OnDayUpdate += OnDayUpdate;
SetBehaivorDateTimes();
Sleep();
Sleep();*/
}
/*
void OnDayUpdate()
{
SetBehaivorDateTimes();
@@ -145,5 +146,5 @@ public class Person : MonoBehaviour
Random.Range(0, 59),
currentDateTime.Second);
}
}*/
}

View File

@@ -1,22 +1,52 @@
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.AI;
public class PersonMovement : MonoBehaviour
{
NavMeshAgent agent;
private int currentPathIndex;
[SerializeField] private List<Vector3> pathVectorList;
private const float speed = 40f;
private void Awake()
{
agent = GetComponent<NavMeshAgent>();
agent.updateRotation = false;
agent.updateUpAxis = false;
//agent.avoidancePriority = Random.Range(1, 100);
}
public void SetTarget(Transform target)
private void Update()
{
agent.SetDestination(target.position);
HandleMovement();
if (Input.GetMouseButton(0))
{
SetTarget(Camera.main.ScreenToWorldPoint(Input.mousePosition));
}
}
void HandleMovement()
{
if (pathVectorList != null)
{
Vector3 targetPosition = pathVectorList[currentPathIndex];
if (Vector3.Distance(transform.position, targetPosition) > 1f)
{
Vector3 moveDir = (targetPosition - transform.position).normalized;
float distanceBefore = Vector3.Distance(transform.position, targetPosition);
transform.position = transform.position + moveDir * speed * Time.deltaTime;
}
else
{
currentPathIndex++;
}
}
}
public Vector3 GetPosition()
{
return transform.position;
}
public void SetTarget(Vector3 targetTransform)
{
pathVectorList = Pathfinding.Instance.FindPath(GetPosition(), targetTransform);
}
}

View File

@@ -1,12 +0,0 @@
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Tile : MonoBehaviour
{
void Start()
{
GetComponent<SpriteRenderer>().color = Random.ColorHSV(0f, 1f, 1f, 1f, 0.5f, 1f);
}
}