Advertisement
spacechase0

collisions

Nov 18th, 2018
144
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 2.18 KB | None | 0 0
  1.         protected void DoCollisions()
  2.         {
  3.             if (!IsSolid())
  4.                 return;
  5.  
  6.             var myColl = GetCollisionBounds();
  7.             var myPrevColl = GetCollisionBounds();
  8.             myPrevColl.Left -= Position.X - PreviousPosition.X;
  9.             myPrevColl.Top -= Position.Y - PreviousPosition.Y;
  10.  
  11.             // Gather colliding entities
  12.             var colls = new List<FloatRect>();
  13.             foreach (var entity in CurrentLocation.GetEntities())
  14.             {
  15.                 if (entity == this)
  16.                     continue;
  17.  
  18.                 var otherColl = entity.GetCollisionBounds();
  19.                
  20.                 if (entity.IsSolid() && otherColl.Intersects(myColl) && !otherColl.Intersects(myPrevColl))
  21.                 {
  22.                     colls.Add(otherColl);
  23.                 }
  24.             }
  25.            
  26.             // TODO: Tiles
  27.            
  28.             // Resolve collisions
  29.             foreach (var otherColl in colls)
  30.             {
  31.                 // Horizontal
  32.                 if (otherColl.Left + otherColl.Width > myColl.Left && otherColl.Left + otherColl.Width <= myPrevColl.Left)
  33.                 {
  34.                     Position.X += (otherColl.Left + otherColl.Width) - myColl.Left;
  35.                     Velocity.X = 0;
  36.                 }
  37.                 else if (otherColl.Left < myColl.Left + myColl.Width && otherColl.Left >= myPrevColl.Left + myPrevColl.Width)
  38.                 {
  39.                     Position.X -= (myColl.Left + myColl.Width) - otherColl.Left;
  40.                     Velocity.X = 0;
  41.                 }
  42.  
  43.                 // Vertical
  44.                 if (otherColl.Top + otherColl.Height > myColl.Top && otherColl.Top + otherColl.Height <= myPrevColl.Top)
  45.                 {
  46.                     Position.Y += (otherColl.Top + otherColl.Height) - myColl.Top;
  47.                     Velocity.Y = 0;
  48.                 }
  49.                 else if (otherColl.Top < myColl.Top + myColl.Height && otherColl.Left >= myPrevColl.Top + myPrevColl.Height)
  50.                 {
  51.                     Position.Y -= (myColl.Top + myColl.Height) - otherColl.Top;
  52.                     Velocity.Y = 0;
  53.                 }
  54.             }
  55.         }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement