Skip to content

Instantly share code, notes, and snippets.

@TinkerWorX
Created June 5, 2012 18:56
Show Gist options
  • Save TinkerWorX/2876953 to your computer and use it in GitHub Desktop.
Save TinkerWorX/2876953 to your computer and use it in GitHub Desktop.
...
private Vector2 ApplyTileCollision(Vector2 deltaVelocity)
{
var deltaPosition = this.Position + deltaVelocity;
// Reset active values, as they are recalculated.
this.ActiveFriction = Single.NaN;
this.ActiveElasticity = Single.NaN;
var startx = this.TileStartX - 1;
var endx = this.TileEndX + 1;
var starty = this.TileStartY - 1;
var endy = this.TileEndY + 1;
TileRegion? horizontalWall = null;
TileRegion? verticalWall = null;
if (this.IsMovingRight)
{
// Make a wall to the right of the entity.
verticalWall = this.realm.GetTileRegion(endx, starty + 1, endx, endy - 1);
}
else if (this.IsMovingLeft)
{
// Make a wall to the left of the entity.
verticalWall = this.realm.GetTileRegion(startx, starty + 1, startx, endy - 1);
}
if (this.IsMovingDown)
{
// Make a floor under the entity.
horizontalWall = this.realm.GetTileRegion(startx + 1, endy, endx - 1, endy);
}
else if (this.IsMovingUp)
{
// Make a ceiling above the entity.
horizontalWall = this.realm.GetTileRegion(startx + 1, starty, endx - 1, starty);
}
// Reset horizontal flags.
this.IsPushingLeft = false;
this.IsPushingRight = false;
if (verticalWall.HasValue && verticalWall.Value.IsSolid)
{
if (this.IsMovingRight && deltaPosition.X + this.Width >= verticalWall.Value.BoundingBox.Left)
{
this.IsPushingRight = true;
deltaVelocity.X = verticalWall.Value.BoundingBox.Left - this.Right - 1.00f;
}
else if (this.IsMovingLeft && deltaPosition.X < verticalWall.Value.BoundingBox.Right)
{
this.IsPushingLeft = true;
deltaVelocity.X = verticalWall.Value.BoundingBox.Right - this.Left;
}
}
// Reset vertical flags.
this.IsPushingDown = false;
this.IsPushingUp = false;
if (horizontalWall.HasValue && horizontalWall.Value.IsSolid)
{
if (this.IsMovingDown && deltaPosition.Y + this.Height >= horizontalWall.Value.BoundingBox.Top)
{
this.ActiveFriction = horizontalWall.Value.Friction;
this.IsPushingDown = true;
if (deltaVelocity.Y > 4.00f)
{
this.ActiveElasticity = horizontalWall.Value.Elasticity;
deltaVelocity.Y = horizontalWall.Value.BoundingBox.Top - this.Bottom - 1.00f;
}
else
{
deltaVelocity.Y = horizontalWall.Value.BoundingBox.Top - this.Bottom - 1.00f;
}
}
else if (this.IsMovingUp && deltaPosition.Y < horizontalWall.Value.BoundingBox.Bottom)
{
this.IsPushingUp = true;
deltaVelocity.Y = horizontalWall.Value.BoundingBox.Bottom - this.Top;
}
}
return deltaVelocity;
}
...
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment