Advertisement
Guest User

Untitled

a guest
Feb 20th, 2017
62
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.76 KB | None | 0 0
  1. #include "stdafx.h"
  2. #include "Actor.h"
  3.  
  4. Actor::Actor(b2World* pWorld, const b2Vec2& startPosition)
  5. {
  6. //Define body
  7. b2BodyDef bd;
  8. bd.position.Set(startPosition.x, startPosition.y);
  9. bd.type = b2_dynamicBody;
  10. bd.allowSleep = false;
  11. bd.linearDamping = 0.01f;
  12. bd.angularDamping = 0.1f;
  13. m_pBody = pWorld->CreateBody(&bd); //Create body
  14. //Define shape
  15. b2CircleShape shape;
  16. shape.m_radius = 1.0f;
  17. //Create fixture
  18. m_pBody->CreateFixture(&shape, 0.0f);
  19.  
  20. //Variables
  21. m_Target = startPosition;
  22. }
  23.  
  24. Actor::~Actor()
  25. {
  26. }
  27.  
  28. void Actor::Update()
  29. {
  30. KinematicSeekAndArrive();
  31. float angle = Orientation(m_pBody->GetAngle(), m_pBody->GetLinearVelocity());
  32. m_pBody->SetTransform(m_pBody->GetPosition(), angle);
  33. }
  34.  
  35. void Actor::Render(Renderer* pRenderer)
  36. {
  37. b2Vec2 pos = m_pBody->GetPosition();
  38. b2Vec2 vel = m_pBody->GetLinearVelocity();
  39. b2Vec2 dir = vel;
  40. dir.Normalize();
  41. dir *= 1.5f;
  42.  
  43. pRenderer->DrawSegment(pos, pos + dir, b2Color(0, 1, 0));
  44. pRenderer->DrawString(pos + b2Vec2(1.0f, -1.0f), "x: %.2f, y: %.2f", vel.x, vel.y);
  45. }
  46.  
  47. void Actor::KinematicSeekAndArrive()
  48. {
  49. //Variables
  50. float radius = 1.0f;
  51. float maximumSpeed = 100.0f;
  52. float timeToTarget = 0.25f;
  53.  
  54. //Calculate direction
  55. b2Vec2 dir = m_Target - m_pBody->GetPosition();
  56. if(dir.Length() < radius)
  57. {
  58. m_pBody->SetLinearVelocity(b2Vec2_zero);
  59. return;
  60. }
  61. b2Vec2 vel = b2Vec2(dir.x / timeToTarget, dir.y / timeToTarget);
  62. if(vel.Length() > maximumSpeed)
  63. {
  64. vel.Normalize();
  65. vel *= maximumSpeed;
  66. }
  67. m_pBody->SetLinearVelocity(vel);
  68. m_pBody->SetAngularVelocity(0.0f);
  69. }
  70.  
  71. float Actor::Orientation(float currOr, const b2Vec2& vel)
  72. {
  73. if(vel.Length() > 0)
  74. {
  75. b2Vec2 dir = vel;
  76. dir.Normalize();
  77. return atan2(-dir.x, dir.x);
  78. }
  79. return currOr;
  80. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement