So I need to be able to auto tile on the X and Y axis for parallax backgrounds with a game I’m developing; I didn’t see anything that would allow me to do this with sprites on the asset store (most require it to be a texture), so I decided to roll my own.
The parallax is working great, and the tiling is adding and removing tiles wonderfully until you start moving very fast. The camera goes faster than the Update can check if it needs to add a new tile, and it eventually deletes all of the tiles since no new ones are created, and it removes ones that get too far from the camera.
Here’s some pseudo-code for how I’m checking to add new tiles:
Add Left If
CamBounds.min.X - SpriteBounds.min.X >= AddThresholdX
Add Right If
SpriteBounds.max.X - CamBounds.max.X >= AddThresholdX
Add Up If
SpriteBounds.max.Y - CamBounds.max.Y >= AddThresholdY
Add Down If
CamBounds.min.Y - SpriteBounds.min.Y >= AddThresholdY
I also have a grid system that makes sure it doesn’t place multiple tiles in the same place.
So this depends on the camera to be close enough to the edge of the texture for it to be able to calculate that it needs to add an adjacent tile. Is this the proper way to go about this, or is there a better way?
Here’s the full tile code block:
foreach (var obj in TiledObjects)
{
#region AutoTileX
if (obj.AutoTileX)
{
if (!obj.hasLeftTile || !obj.hasRightTile)
{
if ((obj.SpriteBounds.max.x - CamBounds.max.x) <= obj.AddThresholdX && !obj.hasRightTile)
{
int rowCheck = obj.row;
int colCheck = obj.col + 1;
if (!TiledObjects.Any(o => o.row == rowCheck && o.col == colCheck))
CreateNewTile(obj, TileDirection.RIGHT);
}
if ((CamBounds.min.x - obj.SpriteBounds.min.x) <= obj.AddThresholdX && !obj.hasLeftTile)
{
int rowCheck = obj.row;
int colCheck = obj.col - 1;
if (TiledObjects.Any(o => o.row == rowCheck && o.col == colCheck))
CreateNewTile(obj, TileDirection.LEFT);
}
}
if ((CamBounds.min.x - obj.SpriteBounds.max.x >= obj.RemoveThresholdX) ||
(obj.SpriteBounds.min.x - CamBounds.max.x >= obj.RemoveThresholdX))
{
if (!TilesToRemove.Contains(obj))
TilesToRemove.Add(obj);
}
}
#endregion
#region AutoTileY
if (obj.AutoTileY)
{
if (!obj.hasTopTile || !obj.hasBottomTile)
{
if (obj.SpriteBounds.max.y - CamBounds.max.y <= obj.AddThresholdY && !obj.hasTopTile)
{
int rowCheck = obj.row - 1;
int colCheck = obj.col;
if (TiledObjects.Any(o => o.row == rowCheck && o.col == colCheck))
CreateNewTile(obj, TileDirection.UP);
}
if (CamBounds.min.y - obj.SpriteBounds.min.y <= obj.AddThresholdY && !obj.hasBottomTile)
{
int rowCheck = obj.row + 1;
int colCheck = obj.col;
if (TiledObjects.Any(o => o.row == rowCheck && o.col == colCheck))
CreateNewTile(obj, TileDirection.DOWN);
}
}
if ((obj.SpriteBounds.min.y - CamBounds.max.y >= obj.RemoveThresholdY) ||
(CamBounds.min.y - obj.SpriteBounds.max.y >= obj.RemoveThresholdY))
{
if (!TilesToRemove.Contains(obj))
TilesToRemove.Add(obj);
}
}
#endregion
}