Game.cpp 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. #include "Game.h"
  2. #include "gaming-core/utils/Utils.h"
  3. #include "rendering/Renderer.h"
  4. #include "utils/StringBuffer.h"
  5. Game::Game(Controller& c, const Clock& fps, const Clock& tps, const Size& size)
  6. : controller(c), fps(fps), tps(tps), size(size), physicsToggle(true),
  7. player(Vector2(50.0f, 50.0f), 5.0f) {
  8. }
  9. void Game::tick() {
  10. if(controller.start.wasReleased()) {
  11. physicsToggle = !physicsToggle;
  12. }
  13. player.preTick();
  14. if(physicsToggle) {
  15. // forces from the player
  16. if(controller.a.isDown() && player.onGround) {
  17. player.addForce(Vector2(0.0f, 70.0f));
  18. player.onGround = false;
  19. }
  20. if(controller.right.isDown()) {
  21. player.addForce(Vector2(2.5f, 0.0f));
  22. }
  23. if(controller.left.isDown()) {
  24. player.addForce(Vector2(-2.5f, 0.0f));
  25. }
  26. // pseudo drag
  27. player.addForce(Vector2(-player.velocity[0] * 0.5f, 0.0f));
  28. } else {
  29. player.velocity[0] = 0.0f;
  30. if(controller.a.isDown() && player.onGround) {
  31. player.velocity[1] = 15.0f;
  32. player.onGround = false;
  33. }
  34. if(controller.right.isDown()) {
  35. player.velocity[0] = 5.0f;
  36. }
  37. if(controller.left.isDown()) {
  38. player.velocity[0] = -5.0f;
  39. }
  40. }
  41. player.tick();
  42. // collision detection
  43. // floor crush
  44. if(player.position[1] < 0.0f) {
  45. player.position[1] = 0.0f;
  46. player.velocity[1] = 0.0f;
  47. player.onGround = true;
  48. }
  49. // right wall
  50. if(player.position[0] + player.size[0] > size.width) {
  51. player.position[0] = size.width - player.size[0];
  52. // player.velocity[0] = 0.0f;
  53. }
  54. // left wall
  55. if(player.position[0] < 0.0f) {
  56. player.position[0] = 0.0f;
  57. // player.velocity[0] = 0.0f;
  58. }
  59. }
  60. void Game::render(float lag, Renderer& r) const {
  61. r.translateTo(0.0f, 0.0f)
  62. .scale(1.0f, -1.0f)
  63. .translateY(size.height)
  64. .update();
  65. Vector2 pos = Utils::interpolate(player.lastPosition, player.position, lag);
  66. r.drawRectangle(pos, player.size, Color4(0xFF, 0x00, 0x00, 0xFF));
  67. r.translateTo(0.0f, 0.0f).update();
  68. r.setStringSize(2);
  69. StringBuffer<100> s("FPS: ");
  70. s.append(fps.getUpdatesPerSecond()).append(" ");
  71. s.append(physicsToggle ? "Force Physics" : "Velocity Physics");
  72. float y = 10.0f;
  73. y = r.drawString(10.0f, y, s);
  74. s.clear().append("a = ").append(player.acceleration);
  75. y = r.drawString(10.0f, y, s);
  76. s.clear().append("v = ").append(player.velocity);
  77. y = r.drawString(10.0f, y, s);
  78. }
  79. bool Game::isRunning() const {
  80. return !controller.select.isDown();
  81. }