1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112
|
#include <SFML/Window.hpp>
#include <SFML/Graphics.hpp>
#include <iostream>
#define WIDTH 1200
#define HEIGHT 1200
typedef enum
{
VEHICLE1,
VEHICLE2,
VEHICLE3,
VEHICLE4,
VEHICLE5,
VEHICLE6
} tVehicleType;
sf::RenderWindow renderWindow(sf::VideoMode(WIDTH, HEIGHT), "Traffic Simulator");
class Vehicle
{
float x;
float y;
float angle;
bool origin_set;
sf::Texture texture; //vehicle texture object
sf::Sprite sprite; //vehicle sprite object
tVehicleType myVehicleType;
public:
//Constructor for the Vehicle class:
// t: Vehicle type
// corx coordinate of the current vehicle position
// cory coordinate of the current vehicle position
// angle: vehicle heading angle, i.e., orientation
Vehicle(tVehicleType, float, float, float, sf::Sprite &, sf::Texture &);
// Moves the vehicle and draws it to screen at the new location:
// x: x coordinate to move the vehicle to
// y: y coordinate to move the vehicle to
// angle: new vehicle heading angle after the move
void move(int, int, float &, float &, sf::Sprite &);
};
Vehicle::Vehicle(tVehicleType vehicleType, float initx, float inity, float initAngle, sf::Sprite &mySprite, sf::Texture &myTexture)
{
this->myVehicleType = vehicleType;
this->x = initx;
this->y = inity;
this->angle = initAngle;
this->sprite = mySprite;
this->texture = myTexture;
// Load the file, "." states the project directory with custom working directory
if (!myTexture.loadFromFile("./images/vehicles/car" + std::to_string(myVehicleType + 1) + ".png", sf::IntRect(0, 0, 64, 32)))
{
std::cout << "Could not load the vehicle image file" << std::endl;
}
mySprite.setTexture(myTexture);
}
void Vehicle::move(int increment, int increment2, float &x, float &y, sf::Sprite &mySprite)
{
x += increment;
y += increment2;
if(x == 150 && y == 150)
{
mySprite.setRotation(0);
increment = 1;
increment2 = 0;
}
else if((x == 239*2 + 90) && y == 150)
{
mySprite.setRotation(90);
increment = 0;
increment2 = 1;
}
else if((x == 239*2 + 90) && y == 239*2 + 150)
{
mySprite.setRotation(0);
increment = 1;
increment2 = 0;
}
else if((x == 239*4 + 90) && y == 239*2 + 150)
{
mySprite.setRotation(90);
increment = 0;
increment2 = 1;
}
else if((x == 239*4 + 90) && y == 239*4 + 90)
{
mySprite.setRotation(180);
increment = -1;
increment2 = 0;
}
else if((x == 150) && y == 239*4 + 90)
{
mySprite.setRotation(270);
increment = 0;
increment2 = -1;
}
}
|