Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- protected void CollisionHandle(List<List<WorldTile>> TileMap)
- {
- int leftTile = (int)Math.Floor((float)_Collbox.Left / WorldTile.Width);
- int rightTile = (int)Math.Ceiling(((float)_Collbox.Right / WorldTile.Width)) - 1;
- int topTile = (int)Math.Floor((float)_Collbox.Top / WorldTile.Height);
- int bottomTile = (int)Math.Ceiling(((float)_Collbox.Bottom / WorldTile.Height)) - 1;
- _OnGround = false;
- for (int y = topTile; y <= bottomTile; y++)
- {
- for (int x = leftTile; x <= rightTile; x++)
- {
- TileCollision collision = TileCollision.Empty;
- if (y >= 0)
- {
- if (x >= 0)
- {
- if (y < TileMap.Count && x < TileMap[y].Count)
- collision = TileMap[y][x].Collision;
- }
- }
- if (collision != TileCollision.Empty)
- {
- _TileBounds = new Rectangle(x * WorldTile.Width, y * WorldTile.Height, WorldTile.Width, WorldTile.Height);
- Vector2 depth = IntersectDepth(_Collbox, _TileBounds);
- if (depth != Vector2.Zero)
- {
- float absDepthX = Math.Abs(depth.X);
- float absDepthY = Math.Abs(depth.Y);
- if (absDepthY <= absDepthX || collision == TileCollision.OneWay)
- {
- if (_PreviousBottom <= _TileBounds.Top)
- _OnGround = true;
- if ((collision == TileCollision.Solid) || _OnGround)
- {
- Position = new Vector2((int)Math.Round(Position.X), (int)Math.Round(Position.Y + depth.Y));
- UpdateCollBox();
- }
- }
- else if (collision == TileCollision.Solid)
- {
- Position = new Vector2((int)Math.Round(Position.X + depth.X), (int)Math.Round(Position.Y));
- _FacingRight = !_FacingRight;
- _Velocity.Y = 0;
- UpdateCollBox();
- }
- }
- }
- }
- }
- _PreviousBottom = _Collbox.Bottom;
- }
- private void UpdateCollBox()
- {
- _Collbox = new Rectangle((int)Math.Round(Position.X), (int)Math.Round(Position.Y), Animation.FrameWidth, Animation.FrameHeight);
- }
- private Vector2 IntersectDepth(Rectangle rectangleA, Rectangle rectangleB)
- {
- float halfWidthA = rectangleA.Width / 2.0f;
- float halfHeightA = rectangleA.Height / 2.0f;
- float halfWidthB = rectangleB.Width / 2.0f;
- float halfHeightB = rectangleB.Height / 2.0f;
- Vector2 centerA = new Vector2(rectangleA.Left + halfWidthA, rectangleA.Top + halfHeightA);
- Vector2 centerB = new Vector2(rectangleB.Left + halfWidthB, rectangleB.Top + halfHeightB);
- float distanceX = centerA.X - centerB.X;
- float distanceY = centerA.Y - centerB.Y;
- float minDistanceX = halfWidthA + halfWidthB;
- float minDistanceY = halfHeightA + halfHeightB;
- // If no intersection is happening, return Vector2.Zero
- if (Math.Abs(distanceX) >= minDistanceX || Math.Abs(distanceY) >= minDistanceY)
- return Vector2.Zero;
- // Calculate instersection depth
- float depthX = distanceX > 0 ? minDistanceX - distanceX : -minDistanceX - distanceX;
- float depthY = distanceY > 0 ? minDistanceY - distanceY : -minDistanceY - distanceY;
- return new Vector2(depthX, depthY);
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement