Unity Rectangle Overlapping - c#

So I got this piece of code that fills the given area of specific size with floor tiles.
while (roomsPlaced < roomCount.maximum)
{
Vector3 randomPosition = RandomPosition();
int roomHeight = GetRandomNumber(8, 15);
int roomWidth = GetRandomNumber(6, 15);
if (OutOfMap(randomPosition, roomHeight,roomWidth))
{
continue;
}
if (roomsPlaced > 0) {
if (Overlaps(new Rect(randomPosition.x, randomPosition.y, roomWidth, roomHeight), roomPositions[roomPositions.Count -1]))
continue;
}
roomPositions.Add(new Rect(randomPosition.x, randomPosition.y, roomWidth, roomHeight));
for (int x = (int)randomPosition.x; x <= (int)randomPosition.x + roomWidth; x++)
{
for (int y = (int)randomPosition.y; y <= (int)randomPosition.y + roomHeight; y++)
{
if (x == randomPosition.x || y == randomPosition.y)
toInstantiate = floorTiles[Random.Range(0, floorTiles.Length)];
GameObject instance = Instantiate(toInstantiate, new Vector3(x, y, 0f), Quaternion.identity) as GameObject;
instance.transform.SetParent(boardHolder);
}
}
roomsPlaced++;
}
And here is function that should check if current rectangle overlaps the last rectangle on the list.
bool Overlaps(Rect rA, Rect rB)
{
return (rA.x < rB.x + rB.width && rA.x + rA.width > rB.x && rA.y < rB.y + rB.height && rA.y + rA.height > rB.y);
}
But still I have problem when some of my rooms overlap.
What am I doing wrong and what should I do to fix this problem ?

This sounds like you need to use the Overlaps method instead...

Yeeah. I just solved the problem by going through the whole list instead of picking last element on the list.

Related

Trying center a tower on tilemap

Iam making a placement system using tilemaps, its almost done but have a small problem.
Placement System
As you can see the tower never be on middle of tiles, i want it always be on middle, even if the size is 2x2 (on that video is 3x3), i dont know what is wrong with my code, so i need help.
void Update()
{
Vector3 mousePosWorldPoint = Camera.main.ScreenToWorldPoint(Input.mousePosition);
Vector3Int cellPos = sniperTower.World.MapGrid.LocalToCell(mousePosWorldPoint);
Vector3 posConverted = sniperTower.World.MapGrid.CellToLocalInterpolated(cellPos);
BoundsInt bounds = new BoundsInt();
bounds.position = cellPos;
bounds.size = sniperTower.BuldingSize;
if (sniperTower.PreviousBounds.position != null && sniperTower.PreviousBounds.position != bounds.position) {
sniperTower.World.clearTiles(sniperTower.PreviousBounds);
sniperTower.Moving(bounds,new Vector3(posConverted.x, posConverted.y, 10));
sniperTower.World.fillTiles("Placing",bounds);
}else if(sniperTower.PreviousBounds.position == null) {
sniperTower.Moving(bounds,new Vector3(posConverted.x, posConverted.y, 10));
sniperTower.World.fillTiles("Placing",bounds);
}
}
//The Moving Method
public virtual void Moving(BoundsInt bounds,Vector3 position){
this.movingBounds = bounds;
this.previousBounds = this.movingBounds;
this.buildingObject.transform.position = position;
}
//The FillTiles and ClearTiles Methods
public void fillTiles(string tileType, BoundsInt area){
for (int x = area.x; x < (area.x + area.size.x); x++) {
for (int y = area.y; y < (area.y + area.size.y); y++) {
placingTilemap.SetTile(new Vector3Int(x,y,0),tiles[tileType]);
}
}
}
public void clearTiles(BoundsInt area){
for (int x = area.x; x < (area.x + area.size.x); x++) {
for (int y = area.y; y < (area.y + area.size.y); y++) {
placingTilemap.SetTile(new Vector3Int(x,y,0),null);
}
}
}

Replacing hexagons with destroyed hexagons

I want to replace the destroyed hexagons with other standing hexagons. Existing hexagons should fall from the top. For example if I destroy (0,2) positioned hexagon in the picture below, the top left hexagon which position of that hexagon is (0,0) should be moved to (0,2) position and i should create a new hexagon and put it on (0,0) which is empty now because we moved the hexagon on (0,0) to (0,2) earlier.
I have a two dimensional array that stores all the references of hexagons with an index of the hexagon's coordinate (x,y).
--IMPORTANT--
Moving the objects is not important. The important part is we have to know which hexagon will be replaced with another. We have to tell the ARRAY that we changed those hexagons and the hexagons that were just moved or created should have exactly one reference in the index of their new (x,y) positions.
VIDEO FOR BETTER EXPLAINING WHAT I WANT TO DO
https://www.youtube.com/watch?v=QYhq0qwFmmY
Any ideas or help would be appreciated!
Hexagon Coordinate system (ignore red arrows)
public void CreateGrid(int gridWidth, int gridHeight)
{
for (int y = 0; y < gridHeight; y++)
{
for (int x = 0; x < gridWidth; x++)
{
GameObject Hexagon = Instantiate(HexagonPre, Vector2.zero, Quaternion.identity, HexGrid);
int RandColor = Random.Range(0, 5);
if (RandColor == 0)
{
Hexagon.GetComponent<SpriteRenderer>().color = Color.blue;
}
else if (RandColor == 1)
{
Hexagon.GetComponent<SpriteRenderer>().color = Color.red;
}
else if (RandColor == 2)
{
Hexagon.GetComponent<SpriteRenderer>().color = Color.green;
}
else if (RandColor == 3)
{
Hexagon.GetComponent<SpriteRenderer>().color = Color.yellow;
}
else if (RandColor == 4)
{
Hexagon.GetComponent<SpriteRenderer>().color = Color.cyan;
}
Vector2 gridPos = new Vector2(x, y);
Hexagon.transform.position = CalcWorldPos(gridPos);
Hexagon.GetComponent<HexCoordinates>().Coordinates = new Vector2Int(x, y);
Hexagon.transform.name = "X: " + x + " | Y: " + y;
}
}
}
Code for destroying hexagons
if (MatchedColors == 2)
{
if(!HexToBeDestroyed.Contains(Hexagons[x, y].gameObject))
HexToBeDestroyed.Add(Hexagons[x, y].gameObject);
if (!HexToBeDestroyed.Contains(Hexagons[x - 1, y].gameObject))
HexToBeDestroyed.Add(Hexagons[x - 1, y].gameObject);
if (!HexToBeDestroyed.Contains(Hexagons[x - 1, y - 1].gameObject))
HexToBeDestroyed.Add(Hexagons[x - 1, y - 1].gameObject);
}
MatchedColors = 0;
}
}
}
}
foreach (GameObject G in HexToBeDestroyed)
{
if (G != null)
{
Destroy(G.gameObject);
}
}
Explanation for code is in comments:
void HexagonFall(GameObject[,] hexArray)
{
// Handle fall for base columns and for offset columns
for (int offset = 0 ; offset < 2 ; offset++)
{
// Handle fall for each column at current offset
for (int x = 0 ; x < hexArray.GetLength(0) ; x++)
{
int bottomYIndex = hexArray.GetLength(1) - offset - 1;
// List of indices of where each hexagon in that column will come from.
// We will fill from bottom to top.
List<Vector2Int> sourceIndices = new List<Vector2Int>();
for (int y = bottomYIndex ; y >= 0 ; y-=2)
{
// HexExists returns true if the hex isn't empty.
// Something along the lines of ` return input!=null; `
// depending on what "empty" hexes look like in the array
if (HexExists(hexArray[x,y]))
{
sourceIndices.Add(new Vector2Int(x,y));
}
}
// We have a list of where to get each bottom hexes from, now do the move/create
for (int y = bottomYIndex; y >= 0 ; y-=2)
{
if (sourceIndices.Count > 0)
{
// If we have any available hexes in column,
// use the bottommost one (at index 0)
hexArray[x,y] = hexArray[sourceIndices[0].x, sourceIndices[0].y];
// We have now found a home for hex previously at sourceIndices[0].
// Remove that index from list so hex will stay put.
sourceIndices.RemoveAt(0);
}
else
{
// Otherwise, we need to generate a new hex
hexArray[x,y] = MakeNewHexAt(new Vector2Int(x,y));
}
// Tell the hex about its new home
hexArray[x,y].GetComponent<HexCoordinates>().Coordinates = new Vector2Int(x, y);
hexArray[x,y].transform.name = "X: " + x + " | Y: " + y;
}
}
}
}
In your hex destroying code, I would change HexToBeDestroyed to be a List of Vector2Int so you can set the array references to null immediately when you Destroy the gameobject:
List<Vector2Int> HexToBeDestroyed = new List<Vector2Int>();
// ...
if (MatchedColors == 2)
{
if(!HexToBeDestroyed.Contains(new Vector2Int(x, y))
HexToBeDestroyed.Add(new Vector2Int(x, y));
if (!HexToBeDestroyed.Contains(new Vector2Int(x - 1, y))
HexToBeDestroyed.Add(new Vector2Int(x - 1, y));
if (!HexToBeDestroyed.Contains(new Vector2Int(x - 1, y - 1)))
HexToBeDestroyed.Add(new Vector2Int(x - 1, y - 1));
}
// ...
foreach (Vector2Int V in HexToBeDestroyed)
{
if (Hexagons[V.x,V.y] != null)
{
Destroy(Hexagons[V.x,V.y]);
Hexagons[V.x,V.y] = null;
}
}
As far as moving the hexes goes, I would add this in the Update of HexCoordinates:
float fallSpeed = 0.5f;
Vector2 goalWorldPosition = GS.CalcWorldPos(Coordinates);
transform.position = Vector2.MoveTowards(transform.position, goalWorldPosition, fallSpeed * Time.deltaTime);

How to debug a recursive function in unity C#

Im trying to make a maze generator using recursion. Its not working how its supposed to work, and Im trying to figure out where the error is. So I want to step through the recursion 1 iteration at the time. How do I do this?
private void DevideRecursive(int pMinX, int pMaxX, int pMinY, int pMaxY)
{
int randomX = Random.Range(pMinX +1, pMaxX);
int randomY = Random.Range(pMinY +1, pMaxY);
int randomWall = Random.Range(0, 4);
List<GameObject> WalllistX1 = new List<GameObject>();
List<GameObject> WalllistX2 = new List<GameObject>();
List<GameObject> WalllistY1 = new List<GameObject>();
List<GameObject> WalllistY2 = new List<GameObject>();
List<List<GameObject>> MainWallList = new List<List<GameObject>>();
MainWallList.Add(WalllistX1);
MainWallList.Add(WalllistX2);
MainWallList.Add(WalllistY1);
MainWallList.Add(WalllistY2);
//// add a wall on a random x coordinate
for (int x = pMinX; x < pMaxX; x++)
{
GameObject wall = Instantiate(WallHor);
wall.transform.position = new Vector2(tilesize * x + tilesize / 2, tilesize * randomY);
if (x < randomX)
{
WalllistX1.Add(wall);
}
else
{
WalllistX2.Add(wall);
}
}
//// add a wall on a random y coordinate
for (int y = pMinY; y < pMaxY ; y++)
{
GameObject wall = Instantiate(WallVer);
wall.transform.position = new Vector2(tilesize * randomX, tilesize * y + tilesize / 2);
if (y < randomY)
{
WalllistY1.Add(wall);
}
else
{
WalllistY2.Add(wall);
}
}
//make a hole in 3 out of tht 4 walls randomly
for (int i = 0; i < MainWallList.Count; i++)
{
if (randomWall != i)
{
RemoveWall(MainWallList[i]);
}
}
////
////
//// If either of the walls have a cell with only 1 grid stop the recursion
Debug.Log("randomX - pMinX:" + (randomX - pMinX));
Debug.Log("pMaxY - randomY:" + (pMaxY - randomY));
Debug.Log("pMaxX - randomX:" + (pMaxX - randomX));
Debug.Log("randomY - pMinY:" + (randomY - pMinY));
if (!(randomX - pMinX <= 1) || !(pMaxY - randomY <= 1))
{
Debug.Log("a");
DevideRecursive(pMinX, randomX, randomY, pMaxY);
}
else
{
return;
}
if (!(pMaxX - randomX <= 1) || !(pMaxY - randomY <= 1))
{
Debug.Log("b");
DevideRecursive(randomX, pMaxX, randomY, pMaxY);
}
else
{
return;
}
if (!(randomX - pMinX <= 1 )|| !(randomY - pMinY <= 1))
{
Debug.Log("c");
DevideRecursive(pMinX, randomX, pMinY, randomY);
}
else
{
return;
}
if (!(pMaxX - randomX <= 1) || !(randomY - pMinY <= 1))
{
Debug.Log("d");
DevideRecursive(randomX, pMaxX, pMinY, randomY);
}
else
{
return;
}
}
This is my Recursive method. It get called in the Start function.
The method creates 2 random walls(1 vertical, 1 horizontal). Which devides the room in 4 smaller rooms. Then it does the same thing for those rooms.
Any help is appriciated
You could modify the function to use async.
using System.Threading.Tasks;
void Start () {
DevideRecursive( ..params.. );
}
private async void DevideRecursive(int pMinX, int pMaxX, int pMinY, int pMaxY) {
// code
while (!Input.GetKeyDown(KeyCode.Space))
await Task.Yield ();
// code
DevideRecursive( .. params .. );
return
}
More infomation on aysnc in Unity here.
An IEnumerator could also be used, which gives you the option to control the function externally.

Tilemap Index out of bounds collision

I created my tile map and my player with movement.
I'm now trying to create the collision and I feel i'm on the right track.
Here is how I've created the map.
List<Texture2D> tileTextures = new List<Texture2D>();
int tileWidth = 60;
int tileHeight = 60;
public int[,] Map = new int[,]
{
{2,2,2,2,2,2,2,2,2,2},
{2,2,2,2,1,2,2,2,2,2},
{2,2,2,2,2,2,2,2,2,2},
{2,2,2,2,2,2,2,2,2,2},
};
public void Draw(SpriteBatch spriteBatch)
{
int tileMapWidth = Map.GetLength(1);
int tileMapHeight = Map.GetLength(0);
for (int x = 0; x < tileMapWidth; x++)
{
for (int y = 0; y < tileMapHeight; y++)
{
int textureIndex = Map[y, x];
Texture2D texture = tileTextures[textureIndex];
spriteBatch.Draw(
texture,
source = new Rectangle(x *myTile.Width,
y * myTile.Height,
tileWidth,
tileHeight),
Color.White);
}
}
}
I am checking the 2d array coords with this condition and checking to see if a specific tile is there, where I can then set my previous location if it is true.
I'm currently testing on 1 tile atm.
public void Update(GameTime gameTime)
{
prevPosition = position;
input(gameTime);
if(tiles.Map[(int)playerPosition.X/60,(int)playerPosition.Y/60] == 1)
{
position = prevPosition;
}
}
However my player position keeps going out of the index bounds of the 2D array and I believe I need to scale it down so that it stops this, I've tried dividing the play coords by the width of the tiles but that hasn't worked.
If anyone can help me with the correct scaling I would be very appreciative.
This will happen if your player's position is like -x,y or x,-y or maybe -x,-y. Yor approach might be better if you'd make a fuction like this one
public bool CollidesWithWall(int x, int y)
{
if(x < 0 || x > *matrix width* - 1) return false;
if(y < 0 || y > *matrix height* -1) return false;
if (Map[x,y] == 1) return true;
return false;
}
and use it insead of the line tiles.Map[(int)playerPosition.X/60,(int)playerPosition.Y/60]
Or, if you need the type of tile returned
public int CollidesWithWall(int x, int y)
{
if(x < 0 || x > *matrix width* - 1) return -1;
if(y < 0 || y > *matrix height* -1) return -1;
return Map[x,y];
}
By doing it this way, you'll know if you stumbled upon a health potion (just set it's ID to like 3) or a wall (with ID of 1 or something, that's tottaly up to you) and if it is 0, it's empty space (or maybe -1). Notice that the "-1" part is totaly up to you. Just write down a list of id's that youll have and which items they present.
Other suggestions
Try if(tiles.Map[(int)(playerPosition.X/60f),(int)(playerPosition.Y/60f)] == 1)

Calculate pixels within a polygon

In an assignment for school do we need to do some image recognizing, where we have to find a path for a robot.
So far have we been able to find all the polygons in the image, but now we need to generate a pixel map, that be used for an astar algorithm later. We have found a way to do this, show below, but the problem is that is very slow, as we go though each pixel and test if it is inside the polygon. So my question is, are there a way that we can generate this pixel map faster?
We have a list of coordinates for the polygon
private List<IntPoint> hull;
The function "getMap" is called to get the pixel map
public Point[] getMap()
{
List<Point> points = new List<Point>();
lock (hull)
{
Rectangle rect = getRectangle();
for (int x = rect.X; x <= rect.X + rect.Width; x++)
{
for (int y = rect.Y; y <= rect.Y + rect.Height; y++)
{
if (inPoly(x, y))
points.Add(new Point(x, y));
}
}
}
return points.ToArray();
}
Get Rectangle is used to limit the search, se we don't have to go thoug the whole image
public Rectangle getRectangle()
{
int x = -1, y = -1, width = -1, height = -1;
foreach (IntPoint item in hull)
{
if (item.X < x || x == -1)
x = item.X;
if (item.Y < y || y == -1)
y = item.Y;
if (item.X > width || width == -1)
width = item.X;
if (item.Y > height || height == -1)
height = item.Y;
}
return new Rectangle(x, y, width-x, height-y);
}
And atlast this is how we check to see if a pixel is inside the polygon
public bool inPoly(int x, int y)
{
int i, j = hull.Count - 1;
bool oddNodes = false;
for (i = 0; i < hull.Count; i++)
{
if (hull[i].Y < y && hull[j].Y >= y
|| hull[j].Y < y && hull[i].Y >= y)
{
try
{
if (hull[i].X + (y - hull[i].X) / (hull[j].X - hull[i].X) * (hull[j].X - hull[i].X) < x)
{
oddNodes = !oddNodes;
}
}
catch (DivideByZeroException e)
{
if (0 < x)
{
oddNodes = !oddNodes;
}
}
}
j = i;
}
return oddNodes;
}
There are some interesting discussion here on polygon hit tests, but it sounds to me as if you might be better off with a polygon fill.
You may want to look for a Plygon Triangulation algorithm.
Also, note that catching an exception is far more time-consuming that checking the right condition. So i suggest you to convert your existing code in:
public bool inPoly(int x, int y)
{
int i, j = hull.Count - 1;
var oddNodes = false;
for (i = 0; i < hull.Count; i++)
{
if (hull[i].Y < y && hull[j].Y >= y
|| hull[j].Y < y && hull[i].Y >= y)
{
var delta = (hull[j].X - hull[i].X);
if (delta == 0)
{
if (0 < x) oddNodes = !oddNodes;
}
else if (hull[i].X + (y - hull[i].X) / delta * delta < x)
{
oddNodes = !oddNodes;
}
}
j = i;
}
return oddNodes;
}

Categories