jeudi 19 août 2021

SFML random shape and movement generation not drawing shape

I have been working on a simple C++ and SFML program recently, but have gotten stuck. Basically I want to do two things:

  1. I want to generate a number of circles with random coordinates
  2. I want to make those circles move randomly around the screen

I figured using a vector for the circles would be best so that I can use am int to determine the number of shapes.

The coordinates are generating correctly, but the shape is not drawing to the screen!

Here is my code:

#include "SFML/Graphics.hpp"
#include <stdlib.h>
#include <iostream>

int main()
{
    srand(time(NULL));

    const int WINDOW_X = 800;
    const int WINDOW_Y = 480;

    sf::RenderWindow window(sf::VideoMode(WINDOW_X, WINDOW_Y), "Epidemic Simulation", sf::Style::Close | sf::Style::Titlebar);

    int numPeople = 2;
    float size = 5;
    int status = 0;

    //Declare CircleShape
    std::vector<sf::CircleShape> person(size);

    //Change color depending on status
    for (int i = 0; i < numPeople; i++)
    {
        if (status == 0)
            person[i].setFillColor(sf::Color::Green);
        else if (status == 1)
            person[i].setFillColor(sf::Color::Red);
        else if (status == 2)
            person[i].setFillColor(sf::Color::Black);
        else
        {
            std::cout << ("Error: Incorrect color value");
            person[i].setFillColor(sf::Color::Green);
        }
    }

    //Generate random coordinates for each circle
    for (int i = 0; i < numPeople; i++)
    {
        int xPos = rand() % WINDOW_X - (size * 2);
        int yPos = rand() % WINDOW_Y - (size * 2);

        if (xPos < (size * 2))
            xPos = 0;

        if (yPos < (size * 2))
            yPos = 0;

        std::cout << ("X position: ") << xPos << (", Y position: ") << yPos << "\n";
    }

    while (window.isOpen())
    {
        sf::Event event;
        while (window.pollEvent(event))
        {
            if (event.type == sf::Event::Closed)
                window.close();
        }

        window.clear(sf::Color::White);

        //Draw circle
        for (int i = 0; i < numPeople; i++)
            window.draw(person[i]);

        window.display();
    }

    return 0;
}

Any idea why the shape is not drawing? And how would I get the shape to move in a random direction?




Aucun commentaire:

Enregistrer un commentaire