2D tile-based collision engine - ideas for improvement?

Started by
5 comments, last by BeerNutts 11 years, 6 months ago
Hi all!

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 dry.png
  • [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 smile.png
Advertisement
wow.. MASSIVE tabs there. Oh well, near enough rolleyes.gif
This is almost unreadable.

Personally I would just do a callback querry for every ingame object. The callback would check for collisions; each collision would map to a different state and/or manipulate a set of data within the object.

This is almost unreadable.

Personally I would just do a callback querry for every ingame object. The callback would check for collisions; each collision would map to a different state and/or manipulate a set of data within the object.


Ok so what you're saying is that the resultant movement should be handled by the game objects themselves and the collision engine should just stick to what its name implies - telling the game object whether it is colliding, what it is colliding with, and any related details that may be of use.. is that right?
Correct, each object will want to react to collisions differently. Every game loop check for collisions, if there are no collisions then don't bother with the callbacks this time around. Make sure to use the Observer pattern, google it if you don't know what it means.
Cool thanks! I'll post my second attempt when done - could be a while, as I'm working on loads of other things in the meantime. At the moment it works 'well enough' dry.png
My suggestion would be to remove the specific Move<SomeDirection> functions, and just use a Move function. You player should have an x and y velocity, and you're movements and collision checking should be based on that. It will make the code much cleaner.

I have replied to similar questions, and you can find them Here and Here

Good luck, and have fun.

My Gamedev Journal: 2D Game Making, the Easy Way

---(Old Blog, still has good info): 2dGameMaking
-----
"No one ever posts on that message board; it's too crowded." - Yoga Berra (sorta)

This topic is closed to new replies.

Advertisement