Advertisement
Guest User

Untitled

a guest
Jan 23rd, 2017
83
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.39 KB | None | 0 0
  1. for each (auto ball in m_Balls)
  2. {
  3. ball->Update(t);
  4. ball->Accelerate(m_Gravity);
  5. }
  6.  
  7. // This disgusting hack sorts the balls by height
  8. // In a more complete physics implementation I guess I could change the sorting based on the direction of gravitational force
  9. // This hack is necessary to prevent balls being pulled downwards into other balls by gravity... By calculating
  10. // From the bottom of the pile of objects, we avoid issues that occur when adjustments push the object towards gravity.
  11. m_Balls.sort([](const CSprite* a, const CSprite* b) { return a->m_pos.m_y < b->m_pos.m_y; });
  12.  
  13. static float cor = 0.8f;
  14.  
  15. for each (auto ball in m_Balls)
  16. {
  17. for each (auto collider in m_Walls)
  18. {
  19. if (collider->HitTest(ball, 1))
  20. {
  21. float offset = 0;
  22. auto n = Helper::GetNormal(ball, collider, offset);
  23.  
  24. ball->SetPosition(ball->GetPosition() + (n * offset));
  25.  
  26. auto r = ball->GetVelocity() - ((1 + cor) * Dot(ball->GetVelocity(), n) * n);
  27.  
  28. ball->SetVelocity(r);
  29.  
  30. ball->SetPosition(ball->GetPosition() + ball->GetVelocity() * DeltaTime());
  31. }
  32. }
  33.  
  34. CVector adjustment;
  35.  
  36. for each (auto collider in m_Balls)
  37. {
  38. if (ball == collider)
  39. {
  40. break;
  41. }
  42.  
  43. auto diff = collider->GetPosition() - ball->GetPosition();
  44.  
  45. float distance = diff.Length();
  46.  
  47. if (distance <= (ball->GetWidth() / 2) + (collider->GetWidth() / 2))
  48. {
  49. auto midPoint = (ball->GetPosition() + collider->GetPosition()) * 0.5f;
  50.  
  51. adjustment = diff.Normalise() * (ball->GetWidth() / 2 - Distance(ball->GetPosition(), midPoint));
  52. ball->SetPosition(ball->GetPosition() - adjustment);
  53. diff = collider->GetPosition() - ball->GetPosition();
  54.  
  55. if (Dot(ball->GetVelocity() - collider->GetVelocity(), diff) > 0)
  56. {
  57. auto n = diff.Normalise();
  58. auto u = Dot(cor * ball->GetVelocity() - collider->GetVelocity(), n) * n;
  59. ball->Accelerate(-u);
  60. collider->Accelerate(u);
  61. }
  62. }
  63. }
  64.  
  65. if (ball->GetSpeed() > MAX_SPEED)
  66. {
  67. ball->SetSpeed(MAX_SPEED);
  68. }
  69. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement