Untitled
unknown
csharp
4 years ago
3.0 kB
6
Indexable
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Tilemaps;
public class AI_Simpleton : MonoBehaviour
{
public Tilemap tilemap;
public TileBase wallTile;
public TileBase destructibleTile;
public float moveDelay = 0.5f;
private float time = 0;
public Vector2 startPosition, endPosition;
public List<Vector2> freePositions;
void Start()
{
CheckFreePositions();
}
void Update()
{
if(time < moveDelay)
{
LerpToPosition();
}
}
void LerpToPosition()
{
transform.position = Vector3.Lerp(startPosition, endPosition, time / moveDelay);
time += Time.deltaTime;
if(time >= moveDelay)
{
freePositions.Clear();
CheckFreePositions();
time = 0;
}
}
void CheckFreePositions()
{
Vector3Int originalCell = tilemap.WorldToCell(transform.position);
//up
if (Cell(originalCell + new Vector3Int(0, 1, 0)))
{
Vector3 cellCenterPosition = tilemap.GetCellCenterWorld(originalCell + new Vector3Int(0, 1, 0));
freePositions.Add(cellCenterPosition);
}
//right
if (Cell(originalCell + new Vector3Int(1, 0, 0)))
{
Vector3 cellCenterPosition = tilemap.GetCellCenterWorld(originalCell + new Vector3Int(1, 0, 0));
freePositions.Add(cellCenterPosition);
}
//down
if (Cell(originalCell + new Vector3Int(0, -1, 0)))
{
Vector3 cellCenterPosition = tilemap.GetCellCenterWorld(originalCell + new Vector3Int(0, -1, 0));
freePositions.Add(cellCenterPosition);
}
//left
if (Cell(originalCell + new Vector3Int(-1, 0, 0)))
{
Vector3 cellCenterPosition = tilemap.GetCellCenterWorld(originalCell + new Vector3Int(-1, 0, 0));
freePositions.Add(cellCenterPosition);
}
SetNewPosition();
}
void SetNewPosition()
{
Vector3Int originalCell = tilemap.WorldToCell(transform.position);
Vector3 cellCenterPosition = tilemap.GetCellCenterWorld(originalCell);
startPosition = cellCenterPosition;
if(freePositions.Count > 0 && freePositions.Count < 2)
{
endPosition = freePositions[0];
}
else if(freePositions.Count > 1)
{
endPosition = freePositions[Random.Range(0, freePositions.Count - 1)];
}
else
{
print("Help, there is no freePositions!");
}
}
bool Cell(Vector3Int cell)
{
TileBase thisTile = tilemap.GetTile(cell);
if (thisTile == wallTile || thisTile == destructibleTile)
{
return false;
}
return true;
}
}
Editor is loading...