So, I currently have a Rectangle that updates with player position, and is the size of the sprite. I'm using Tiled as my tile editor, and have an Object layer called "collision" which I loop over when loading the map, and store each object as a Rectangle in a list. Then in my Update I check if the player is colliding with any of those rectangles (via looping over the list) with Rectangle.Intersects(Rectangle). And if a collision is detected, I handle it with this function:
private static void HandleCollision()
{
if (_currentLevel.IsCollisionTile())
{
float deltaLeft = Math.Abs((Player.Instance.Position.X + Player.Instance.PlayerCollider.Width) - (_currentLevel.collidingRectangle.X));
float deltaRight = Math.Abs((Player.Instance.Position.X) + (_currentLevel.collidingRectangle.X + _currentLevel.collidingRectangle.Width));
float deltaUp = Math.Abs((Player.Instance.Position.Y + Player.Instance.PlayerCollider.Height) - (_currentLevel.collidingRectangle.Y));
float deltaDown = Math.Abs((Player.Instance.Position.Y) - (_currentLevel.collidingRectangle.Y + _currentLevel.collidingRectangle.Height));
if (deltaLeft < deltaRight && deltaLeft < deltaUp && deltaLeft < deltaDown)
{
Player.Instance.Position.X -= deltaLeft;
}
else if (deltaRight < deltaLeft && deltaRight < deltaUp && deltaRight < deltaDown)
{
Player.Instance.Position.X += deltaRight;
}
else if (deltaUp < deltaLeft && deltaUp < deltaRight && deltaUp < deltaDown)
{
Player.Instance.Position.Y -= deltaUp;
}
else if (deltaDown < deltaLeft && deltaDown < deltaRight && deltaDown < deltaUp)
{
Player.Instance.Position.Y += deltaDown;
}
}
}
I know this is ugly, but that's not the problem, the problem is that when it detects a collision, the player "spazzes out" and just bounces in and out of the rectangle it's colliding with. I've tried a couple other ways too, like just setting the player position without using absolute values, with similar calculations. The same problem happens though. Also it allows the player to just phase through platforms from one side, and the player will get teleported to other sides sometimes, so this is very bad.
I'm not sure how else to handle it, I've done research and googled a lot, as well as searched here, but everything I find is about the actual collision detection, which I'm doing via the Rectangle.Intersects() method. I've been at this for 3-4 days, before deciding to post here.