Skip to content

Instantly share code, notes, and snippets.

@TinkerWorX
Created December 22, 2014 22:36
Show Gist options
  • Save TinkerWorX/acf1b59eee4952a2c529 to your computer and use it in GitHub Desktop.
Save TinkerWorX/acf1b59eee4952a2c529 to your computer and use it in GitHub Desktop.
foreach (var wall in walls)
{
/*
╔═T═╗
L R
╚═B═╝
*/
var bounds = wall.Bounds;
var point = Vector2.Zero;
var top = bounds.Top;
var bottom = bounds.Bottom;
var left = bounds.Left;
var right = bounds.Right;
var x = current.Position.X;
var y = current.Position.Y;
#region Corners
if (x < left && y < top)
{
point = new Vector2(left, top);
if (current.HasOverlap(point))
{
hasAnyOverlap = true;
var dx = current.Position.X - point.X;
var dy = current.Position.Y - point.Y;
var sr = current.Radius;
var d = Math.Sqrt(dx * dx + dy * dy);
current.Position.X = (Single)(point.X + (dx / d) * sr);
current.Position.Y = (Single)(point.Y + (dy / d) * sr);
}
}
if (x > right && y < top)
{
point = new Vector2(right, top);
if (current.HasOverlap(point))
{
hasAnyOverlap = true;
var dx = current.Position.X - point.X;
var dy = current.Position.Y - point.Y;
var sr = current.Radius;
var d = Math.Sqrt(dx * dx + dy * dy);
current.Position.X = (Single)(point.X + (dx / d) * sr);
current.Position.Y = (Single)(point.Y + (dy / d) * sr);
}
}
if (x < left && y > bottom)
{
point = new Vector2(left, bottom);
if (current.HasOverlap(point))
{
hasAnyOverlap = true;
var dx = current.Position.X - point.X;
var dy = current.Position.Y - point.Y;
var sr = current.Radius;
var d = Math.Sqrt(dx * dx + dy * dy);
current.Position.X = (Single)(point.X + (dx / d) * sr);
current.Position.Y = (Single)(point.Y + (dy / d) * sr);
}
}
if (x > right && y > bottom)
{
point = new Vector2(right, bottom);
if (current.HasOverlap(point))
{
hasAnyOverlap = true;
var dx = current.Position.X - point.X;
var dy = current.Position.Y - point.Y;
var sr = current.Radius;
var d = Math.Sqrt(dx * dx + dy * dy);
current.Position.X = (Single)(point.X + (dx / d) * sr);
current.Position.Y = (Single)(point.Y + (dy / d) * sr);
}
}
#endregion Corners
#region Edges
if (x > left && x < right && y < top)
{
hasAnyOverlap = true;
if (y + current.Radius > top)
current.Position.Y = top - current.Radius;
}
if (x > left && x < right && y > bottom)
{
hasAnyOverlap = true;
if (y - current.Radius < bottom)
current.Position.Y = bottom + current.Radius;
}
if (y > top && y < bottom && x < left)
{
hasAnyOverlap = true;
if (x + current.Radius > left)
current.Position.X = left - current.Radius;
}
if (y > top && y < bottom && x > left)
{
hasAnyOverlap = true;
if (x - current.Radius < right)
current.Position.X = right + current.Radius;
}
#endregion Edges
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment