AllenYuan

Untitled

May 30th, 2020
95
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.10 KB | None | 0 0
  1. #include <SFML/Graphics.hpp>
  2. #include <math.h>
  3. using namespace sf;
  4.  
  5. int main()
  6. {
  7. RenderWindow app(VideoMode(640, 480), "Car Racing Game!");
  8. app.setFramerateLimit(60);
  9.  
  10. Texture t1, t2;
  11. t1.loadFromFile("/Users/alleyuan/code-snippets/16_games/07 Top Down Racing/images/background.png");
  12. t2.loadFromFile("/Users/alleyuan/code-snippets/16_games/07 Top Down Racing/images/car.png");
  13.  
  14. Sprite sBackground(t1), sCar(t2);
  15. sCar.setPosition(300, 300);
  16. sCar.setOrigin(22,22);
  17.  
  18. float x=300, y=300;
  19. float speed = 0, angle = 0; // initial speed/angle (angle=direciton from car center)
  20. float maxSpeed = 12.0;
  21. float acc = 0.2, dec = 0.3; // acceleration.deceleration
  22. float turnSpeed = 0.06; // angular velocity when turning
  23.  
  24. while (app.isOpen())
  25. {
  26. Event e;
  27. while (app.pollEvent(e))
  28. {
  29. if (e.type == Event::Closed)
  30. app.close();
  31. }
  32.  
  33. // set directions
  34. bool Up = 0, Right = 0, Down = 0, Left = 0;
  35. if (Keyboard::isKeyPressed(Keyboard::Up)) Up = 1;
  36. if (Keyboard::isKeyPressed(Keyboard::Right)) Right = 1;
  37. if (Keyboard::isKeyPressed(Keyboard::Down)) Down = 1;
  38. if (Keyboard::isKeyPressed(Keyboard::Left)) Left = 1;
  39.  
  40. // CAR MOVEMENT
  41. // positive speed
  42. if (Up && speed < maxSpeed)
  43. {
  44. if (speed < 0) speed += dec;
  45. else speed += acc;
  46. }
  47.  
  48. // negative speed
  49. if (Down && speed > -maxSpeed)
  50. {
  51. if (speed > 0) speed -= dec;
  52. else speed -= acc;
  53. }
  54.  
  55. // friction
  56. if (!Up && !Down)
  57. {
  58. if (speed - dec > 0) speed -= dec;
  59. else if (speed + dec < 0) speed += dec;
  60. else speed = 0;
  61. }
  62.  
  63. // angle
  64. if (Right && speed != 0) angle += turnSpeed * speed/maxSpeed;
  65. if (Left && speed != 0) angle -= turnSpeed * speed/maxSpeed;
  66.  
  67. // set new position and orientation
  68. x += sin(angle) * speed;
  69. y -= cos(angle) * speed;
  70.  
  71. sCar.setPosition(x, y);
  72. sCar.setRotation(angle*180/3.141592);
  73.  
  74. app.clear(Color::White);
  75. app.draw(sBackground);
  76.  
  77. sCar.setColor(Color::Red);
  78. app.draw(sCar);
  79.  
  80. app.display();
  81. }
  82.  
  83. return 0;
  84. }
Advertisement
Add Comment
Please, Sign In to add comment