Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <SFML/Graphics.hpp>
- using namespace sf;
- int width = 1024;
- int height = 768;
- int roadW = 2000; // road width
- int segL = 200; // segment length
- float camD = 0.84; // base scale factor for distant objects
- // a line in the 3d world w/ a 'project' method to draw it on the 2d screen
- struct Line
- {
- float x,y,z; // 3d center of line
- float X,Y,W; // paramterization of line on screen
- float scale;
- Line() { x=y=z=0; }
- // project the line from 3d world onto 2d screen. X=horizontal, Y=vertical, Z=depth
- void project(int camX, int camY, int camZ)
- {
- scale = camD/(z-camZ); // scale factor for the line. An object looks bigger when its closer (smaller z) and smaller when its farther (large z)
- // lines are closer to the center and smaller when they are far away.
- X = (1 + scale*(x - camX)) * width/2;
- Y = (1 - scale*(y - camY)) * height/2;
- W = scale * roadW * width/2;
- }
- };
- // draw a quadrilateral in w with color c, parameterized by two center points of opposing sides
- // (x1, y1), (x2, y2) and 2 radiuses w1, w2.
- // You may wonder why we parameterize with w1 and w2 instead of 2 more points...this paramterization
- // makes the math for perspectives easier
- void drawQuad(RenderWindow &w, Color c, int x1, int y1, int w1, int x2, int y2, int w2)
- {
- ConvexShape shape(4);
- shape.setFillColor(c);
- shape.setPoint(0, Vector2f(x1-w1, y1));
- shape.setPoint(1, Vector2f(x2-w2, y2));
- shape.setPoint(2, Vector2f(x2+w2, y2));
- shape.setPoint(3, Vector2f(x1+w1, y1));
- w.draw(shape);
- }
- int main()
- {
- RenderWindow app(VideoMode(width, height), "Outrun Racing!");
- app.setFramerateLimit(60);
- // data for 1600 segments (side of the road)
- std::vector<Line> lines;
- for (int i = 0; i < 1600; i++)
- {
- Line line;
- line.z = i * segL;
- lines.push_back(line);
- }
- int N = lines.size();
- while (app.isOpen())
- {
- Event e;
- while (app.pollEvent(e))
- {
- if (e.type == Event::Closed)
- app.close();
- }
- app.clear();
- // draw road
- for (int n = 0; n < 300; n++)
- {
- Line &l = lines[n%N]; // select line to render
- l.project(0, 1500, 0);
- // alternate grass/rumble/road color every 6 lines
- Color grass = (n/3)%2 ? Color(16,200,16) : Color(0,154,0);
- Color rumble = (n/3)%2 ? Color(255,255,255) : Color(0,0,0);
- Color road = (n/3)%2 ? Color(107,107,107) : Color(105,105,105);
- Line p = lines[(n-1)%N]; // previous line
- drawQuad(app, grass, 0, p.Y, width, 0, l.Y, width); // draw grass across the whole screen
- drawQuad(app, rumble, p.X, p.Y, p.W*1.2, l.X, l.Y, l.W*1.2); // draw rumble across the middle of the screen
- drawQuad(app, road, p.X, p.Y, p.W, l.X, l.Y, l.W); // draw road in center of screen
- }
- app.display();
- }
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment