AllenYuan

Untitled

May 30th, 2020
49
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.31 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.08; // angular velocity when turning
  23.  
  24. int offsetX = 0, offsetY = 0;
  25.  
  26.  
  27.  
  28. while (app.isOpen())
  29. {
  30. Event e;
  31. while (app.pollEvent(e))
  32. {
  33. if (e.type == Event::Closed)
  34. app.close();
  35. }
  36.  
  37. // set directions
  38. bool Up = 0, Right = 0, Down = 0, Left = 0;
  39. if (Keyboard::isKeyPressed(Keyboard::Up)) Up = 1;
  40. if (Keyboard::isKeyPressed(Keyboard::Right)) Right = 1;
  41. if (Keyboard::isKeyPressed(Keyboard::Down)) Down = 1;
  42. if (Keyboard::isKeyPressed(Keyboard::Left)) Left = 1;
  43.  
  44. // CAR MOVEMENT
  45. // positive speed
  46. if (Up && speed < maxSpeed)
  47. {
  48. if (speed < 0) speed += dec;
  49. else speed += acc;
  50. }
  51.  
  52. // negative speed
  53. if (Down && speed > -maxSpeed)
  54. {
  55. if (speed > 0) speed -= dec;
  56. else speed -= acc;
  57. }
  58.  
  59. // friction
  60. if (!Up && !Down)
  61. {
  62. if (speed - dec > 0) speed -= dec;
  63. else if (speed + dec < 0) speed += dec;
  64. else speed = 0;
  65. }
  66.  
  67. // angle
  68. if (Right && speed != 0) angle += turnSpeed * speed/maxSpeed;
  69. if (Left && speed != 0) angle -= turnSpeed * speed/maxSpeed;
  70.  
  71. // set new position and orientation
  72. x += sin(angle) * speed;
  73. y -= cos(angle) * speed;
  74.  
  75. if (x > 320) offsetX = x - 320;
  76. if (y > 240) offsetY = y - 240;
  77.  
  78. app.clear(Color::White);
  79. sBackground.setPosition(-offsetX, -offsetY); // follow the car w/ the camera
  80. app.draw(sBackground);
  81.  
  82. sCar.setPosition(x - offsetX, y - offsetY);
  83. sCar.setRotation(angle*180/3.141592);
  84.  
  85. sCar.setColor(Color::Red);
  86. app.draw(sCar);
  87.  
  88. app.display();
  89. }
  90.  
  91. return 0;
  92. }
Advertisement
Add Comment
Please, Sign In to add comment