AllenYuan

Untitled

Jun 13th, 2020
42
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.36 KB | None | 0 0
  1. #include <SFML/Graphics.hpp>
  2. using namespace sf;
  3.  
  4. int width = 1024;
  5. int height = 768;
  6. int roadW = 2000;
  7. int segL = 200; // segment length
  8. float camD = 0.84; // camera depth
  9.  
  10. struct Line
  11. {
  12. float x,y,z; // center of line in the 3d world
  13. float X,Y,W; // parameterization of the line on the screen
  14. float scale;
  15.  
  16. Line() { x=y=z=0; }
  17.  
  18. // project onto the given camera position
  19. void project(int camX, int camY, int camZ)
  20. {
  21. scale = camD/(z-camZ);
  22. X = (1 + scale*(x - camX)) * width/2;
  23. Y = (1 - scale*(y - camY)) * height/2;
  24. W = scale * roadW * width/2;
  25. }
  26. };
  27.  
  28. // draw a quadtrilateral parameterized by two midpoints (x1,y1), (x2,y2) and 2 widths w1, w2.
  29. void drawQuad(RenderWindow &w, Color c, int x1, int y1, int w1, int x2, int y2, int w2)
  30. {
  31. ConvexShape shape(4);
  32. shape.setFillColor(c);
  33. shape.setPoint(0, Vector2f(x1-w1,y1));
  34. shape.setPoint(1, Vector2f(x2-w2, y2));
  35. shape.setPoint(2, Vector2f(x2+w2, y2));
  36. shape.setPoint(3, Vector2f(x1+w1, y1));
  37.  
  38. w.draw(shape);
  39. }
  40.  
  41. int main()
  42. {
  43. RenderWindow app(VideoMode(width, height), "Outrun Racing!");
  44. app.setFramerateLimit(60);
  45.  
  46. std::vector<Line> lines;
  47.  
  48. for (int i = 0; i < 1600; i++)
  49. {
  50. Line line;
  51. line.z = i * segL;
  52.  
  53. lines.push_back(line);
  54. }
  55.  
  56. int N = lines.size();
  57. int pos = 0;
  58. int playerX = 0;
  59.  
  60. while(app.isOpen())
  61. {
  62. Event e;
  63. while (app.pollEvent(e))
  64. {
  65. if (e.type == Event::Closed)
  66. app.close();
  67. }
  68.  
  69. if (Keyboard::isKeyPressed(Keyboard::Right)) playerX += 200;
  70. if (Keyboard::isKeyPressed(Keyboard::Left)) playerX -= 200;
  71. if (Keyboard::isKeyPressed(Keyboard::Up)) pos += 200;
  72. if (Keyboard::isKeyPressed(Keyboard::Down)) pos -= 200;
  73.  
  74. app.clear();
  75. int startPos = pos/segL;
  76.  
  77. for (int n = startPos; n < startPos+300; n++)
  78. {
  79. Line &l = lines[n%N];
  80. l.project(playerX, 1500, pos);
  81.  
  82. Color grass = (n/3)%2?Color(16,200,16):Color(0,154,0);
  83. Color rumble = (n/3)%2?Color(255,255,255):Color(0,0,0);
  84. Color road = (n/3)%2?Color(107,107,107):Color(105,105,105);
  85.  
  86. Line p = lines[(n-1)%N]; // prev line
  87.  
  88. drawQuad(app, grass, 0, p.Y, width, 0, l.Y, width);
  89. drawQuad(app, rumble, p.X, p.Y, p.W*1.2, l.X, l.Y, l.W*1.2);
  90. drawQuad(app, road, p.X, p.Y, p.W, l.X, l.Y, l.W);
  91. }
  92.  
  93. app.display();
  94. }
  95.  
  96. return 0;
  97. }
Advertisement
Add Comment
Please, Sign In to add comment