Just made a collision engine for my 2D tile based game, pieced together from what I've found/learnt from sites like this. Currently it works well enough, but I fear that with my limited testing, it's probably a bit buggy and not very well optimised. It may even be totally the wrong approach lol..
As such I thought I'd share it up for others to use & perhaps find ways to improve!
I'm using it for a platformer style game where each character has a collision rectangle, and the main thing that it does that may be a bit unorthodox is that they are allowed to 'step' up and down tiles depending on the height of the step (in tiles). This is because for my game, each tile is effectively a pixel of the level texture, and for ramps I don't want the character to have to jump up or fall down each pixel.
Things I already know about & haven't had the time to fix/implement:
- [bug] there's definitely some issues with stepping down into gaps the same width as the rectangle (i.e. dropping too early)
- [bug] the rectangle doesn't fit into holes the exact same width as it. They do however fit into holes the same height.
- [bug/feature] Rectangles cannot 'step' down through zones the exact same height as themselves - i.e. if there is *just* enough room in a tunnel for the rectangle to get through, it would need to move down by itself rather than step - probably just a matter of not checking the top row of tiles when it is possible to step down..
- [tidy] The 'Move' methods are almost exact duplicates of each other - I'm a bit OCD about avoiding code duplication and this irritates me
- [performance] It can probably be heavily optimised!
- [possible bug] I haven't tested this in any tilesize other than (1f, 1f)...
Anyway, here it is:
public interface ITile
{
bool Passable{ get; }
}
public interface ILevel
{
Vector2 TileSize{ get; }
ITile GetTileAt( int x, int y );
}
public class CollisionEngine : MonoBehaviour
{
//TODO: null check all level tile access (could be out of range)
public class CollisionResults
{
public bool CollidedX = false;
public bool CollidedY = false;
}
private ILevel m_level = null;
public CollisionEngine( Level level )
{
m_level = level;
}
private Vector2 UpdatePosition( Rect rect, Vector2 moveAmount, int maxStepAmount, out CollisionResults results )
{
Vector2 resultantPos = new Vector2( rect.x, rect.y );
results = new CollisionResults();
bool hasStepped = false;
if( moveAmount.x != 0 )
{
int totalStepAmount = 0;
int startMinY = GetRowIdx( rect.yMin, false );
int startMaxY = GetRowIdx( rect.yMax, true );
if( moveAmount.x < 0 ) // moving left
{
int startMinX = GetColumnIdx( rect.xMin, false );
int endMinX = GetColumnIdx( rect.xMin + moveAmount.x, false );
for( int x = startMinX; x > endMinX; --x )
{
float xDistThisIteration = (float)(x - startMinX) * m_level.TileSize.x;
int steppedAmount;
results.CollidedX = MoveLeft( GetColumnIdx( rect.xMin + xDistThisIteration, false ), // left
startMaxY, // top
GetColumnIdx( rect.xMax + xDistThisIteration, true ), // right
startMinY, // bottom
maxStepAmount,
out steppedAmount );
if( results.CollidedX )
{
// can't move left
resultantPos.x = (float)x * m_level.TileSize.x;
break;
}
else
{
totalStepAmount += steppedAmount;
startMinY += steppedAmount;
startMaxY += steppedAmount;
}
}
}
else // moving right
{
int startMaxX = GetColumnIdx( rect.xMax, true );
int endMaxX = GetColumnIdx( rect.xMax + moveAmount.x, true );
for( int x = startMaxX; x < endMaxX; ++x )
{
float xDistThisIteration = (float)(x - startMaxX) * m_level.TileSize.x;
int steppedAmount;
results.CollidedX = MoveRight( GetColumnIdx( rect.xMin + xDistThisIteration, false ), // left
startMaxY, // top
GetColumnIdx( rect.xMax + xDistThisIteration, true ), // right
startMinY, // bottom
maxStepAmount,
out steppedAmount );
if( results.CollidedX )
{
resultantPos.x = ((float)(x + 1) * m_level.TileSize.x) - rect.width;
break;
}
else
{
totalStepAmount += steppedAmount;
startMinY += steppedAmount;
startMaxY += steppedAmount;
}
}
}
if( !results.CollidedX )
{
resultantPos.x = rect.xMin + moveAmount.x;
}
if( totalStepAmount != 0 )
{
resultantPos.y = Mathf.Floor( rect.yMin ) + ((float)(totalStepAmount) * m_level.TileSize.y);
hasStepped = true;
}
}
if( moveAmount.y != 0 &&
!hasStepped )
{
int startMinX = GetColumnIdx( rect.xMin, false );
int startMaxX = GetColumnIdx( rect.xMax, true );
if( moveAmount.y < 0 ) // moving down
{
int startMinY = GetRowIdx( rect.yMin, false );
int endMinY = GetRowIdx( rect.yMin + moveAmount.y, false );
for( int y = startMinY; y > endMinY; --y )
{
float yDistThisIteration = (float)(y - startMinY) * m_level.TileSize.y;
results.CollidedY = MoveDown( startMinX, // left
GetRowIdx( rect.yMax + yDistThisIteration, true ), // top
startMaxX, // right
GetRowIdx( rect.yMin + yDistThisIteration, false ) ); // bottom
if( results.CollidedY )
{
// can't move down
resultantPos.y = (float)y * m_level.TileSize.y;
break;
}
}
}
else // moving up
{
int startMaxY = GetRowIdx( rect.yMax, true );
int endMaxY = GetRowIdx( rect.yMax + moveAmount.y, true );
for( int y = startMaxY; y < endMaxY; ++y )
{
float yDistThisIteration = (float)(y - startMaxY) * m_level.TileSize.y;
results.CollidedY = MoveUp( startMinX, // left
GetRowIdx( rect.yMax + yDistThisIteration, true ), // top
startMaxX, // right
GetRowIdx( rect.yMin + yDistThisIteration, false ) ); // bottom
if( results.CollidedY )
{
// can't move up
resultantPos.y = ((float)(y + 1) * m_level.TileSize.y) - rect.height;
break;
}
}
}
if( !results.CollidedY )
{
resultantPos.y = rect.yMin + moveAmount.y;
}
}
return resultantPos;
}
private bool MoveLeft( int left, int top, int right, int bottom, int maxStepAmount, out int steppedAmount )
{
bool collided = false;
steppedAmount = 0;
for( int y = bottom; y <= top; ++y )
{
if( !m_level.GetTileAt( left - 1, y ).Passable )
{
// try to step up the tiles if they're within stepping range
if( y < bottom + maxStepAmount )
{
steppedAmount = y - bottom + 1;
}
else
{
collided = true;
break;
}
}
}
if( !collided )
{
if( steppedAmount == 0 &&
!m_level.GetTileAt( right + 1, bottom - 1 ).Passable ) // otherwise we would try to step down while completely airborne
{
// check if we can drop within stepping distance
for( int yStep = 0; yStep < maxStepAmount + 1; ++yStep )
{
if( !MoveDown( left - 1, top - yStep, right - 1, bottom - yStep ) )
{
// if we're not on the last iteration (i.e. too far to step)
if( yStep != maxStepAmount )
{
steppedAmount = -yStep - 1;
}
else
{
steppedAmount = 0;
}
}
}
}
else
{
for( int yStep = 0; yStep < steppedAmount; ++yStep )
{
collided = MoveUp( left, top + yStep, right, bottom + yStep );
if( collided )
{
steppedAmount = 0;
break;
}
}
}
}
return collided;
}
private bool MoveRight( int left, int top, int right, int bottom, int maxStepAmount, out int steppedAmount )
{
bool collided = false;
steppedAmount = 0;
for( int y = bottom; y <= top; ++y )
{
if( !m_level.GetTileAt( right + 1, y ).Passable )
{
// try to step up the tiles if they're within stepping range
if( y < bottom + maxStepAmount )
{
steppedAmount = y - bottom + 1;
}
else
{
collided = true;
break;
}
}
}
if( !collided )
{
if( steppedAmount == 0 &&
!m_level.GetTileAt( left - 1, bottom - 1 ).Passable ) // otherwise we would try to step down while completely airborne
{
// check if we can drop within stepping distance
for( int yStep = 0; yStep < maxStepAmount + 1; ++yStep )
{
if( !MoveDown( left + 1, top - yStep, right + 1, bottom - yStep ) )
{
// if we're not on the last iteration (i.e. too far to step)
if( yStep != maxStepAmount )
{
steppedAmount = -yStep - 1;
}
else
{
steppedAmount = 0;
}
}
}
}
else
{
for( int yStep = 0; yStep < steppedAmount; ++yStep )
{
collided = MoveUp( left, top + yStep, right, bottom + yStep );
if( collided )
{
steppedAmount = 0;
break;
}
}
}
}
return collided;
}
private bool MoveUp( int left, int top, int right, int bottom )
{
bool collided = false;
for( int x = left; x <= right; ++x )
{
if( !m_level.GetTileAt( x, top + 1 ).Passable )
{
collided = true;
break;
}
}
return collided;
}
private bool MoveDown( int left, int top, int right, int bottom )
{
bool collided = false;
for( int x = left; x <= right; ++x )
{
if( !m_level.GetTileAt( x, bottom - 1 ).Passable )
{
collided = true;
break;
}
}
return collided;
}
/// <param name="roundDown">Return the left column index if we are perfectly between columns, as opposed to the right.</param>
private int GetColumnIdx( float worldPosX, bool roundDown )
{
// cater for floating point inaccuracies - if we are aligned to a column we don't want to incorrectly position ourselves in the next one.
float xf = worldPosX / m_level.TileSize.x;
int xIdx;
if( Mathf.Approximately( xf, Mathf.Round( xf ) ) )
{
xIdx = roundDown ? (Mathf.RoundToInt( xf ) - 1) : (Mathf.RoundToInt( xf ));
}
else
{
xIdx = Mathf.FloorToInt( xf );
}
return Mathf.Clamp( xIdx, 0, m_level.Columns - 1 );
}
/// <param name="roundDown">Return the lower row index if we are perfectly between columns, as opposed to the right.</param>
private int GetRowIdx( float worldPosY, bool roundDown )
{
// cater for floating point inaccuracies - if we are aligned to a row we don't want to incorrectly position ourselves in the next one.
float yf = worldPosY / m_level.TileSize.y;
int yIdx;
if( Mathf.Approximately( yf, Mathf.Round( yf ) ) )
{
yIdx = roundDown ? (Mathf.RoundToInt( yf ) - 1) : (Mathf.RoundToInt( yf ));
}
else
{
yIdx = Mathf.FloorToInt( yf );
}
return Mathf.Clamp( yIdx, 0, m_level.Rows - 1 );
}
}
Any feedback welcome