Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <SFML/Graphics.hpp>
- #include <math.h>
- using namespace sf;
- int main()
- {
- RenderWindow app(VideoMode(640, 480), "Car Racing Game!");
- app.setFramerateLimit(60);
- Texture t1, t2;
- t1.loadFromFile("/Users/alleyuan/code-snippets/16_games/07 Top Down Racing/images/background.png");
- t2.loadFromFile("/Users/alleyuan/code-snippets/16_games/07 Top Down Racing/images/car.png");
- Sprite sBackground(t1), sCar(t2);
- sCar.setPosition(300, 300);
- sCar.setOrigin(22,22);
- float x=300, y=300;
- float speed = 0, angle = 0; // initial speed/angle (angle=direciton from car center)
- float maxSpeed = 12.0;
- float acc = 0.2, dec = 0.3; // acceleration.deceleration
- float turnSpeed = 0.08; // angular velocity when turning
- int offsetX = 0, offsetY = 0;
- while (app.isOpen())
- {
- Event e;
- while (app.pollEvent(e))
- {
- if (e.type == Event::Closed)
- app.close();
- }
- // set directions
- bool Up = 0, Right = 0, Down = 0, Left = 0;
- if (Keyboard::isKeyPressed(Keyboard::Up)) Up = 1;
- if (Keyboard::isKeyPressed(Keyboard::Right)) Right = 1;
- if (Keyboard::isKeyPressed(Keyboard::Down)) Down = 1;
- if (Keyboard::isKeyPressed(Keyboard::Left)) Left = 1;
- // CAR MOVEMENT
- // positive speed
- if (Up && speed < maxSpeed)
- {
- if (speed < 0) speed += dec;
- else speed += acc;
- }
- // negative speed
- if (Down && speed > -maxSpeed)
- {
- if (speed > 0) speed -= dec;
- else speed -= acc;
- }
- // friction
- if (!Up && !Down)
- {
- if (speed - dec > 0) speed -= dec;
- else if (speed + dec < 0) speed += dec;
- else speed = 0;
- }
- // angle
- if (Right && speed != 0) angle += turnSpeed * speed/maxSpeed;
- if (Left && speed != 0) angle -= turnSpeed * speed/maxSpeed;
- // set new position and orientation
- x += sin(angle) * speed;
- y -= cos(angle) * speed;
- if (x > 320) offsetX = x - 320;
- if (y > 240) offsetY = y - 240;
- app.clear(Color::White);
- sBackground.setPosition(-offsetX, -offsetY); // follow the car w/ the camera
- app.draw(sBackground);
- sCar.setPosition(x - offsetX, y - offsetY);
- sCar.setRotation(angle*180/3.141592);
- sCar.setColor(Color::Red);
- app.draw(sCar);
- app.display();
- }
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment