SFML community forums

Help => General => Topic started by: Suixle on May 22, 2015, 03:38:57 am

Title: How to randomly create rectangles?
Post by: Suixle on May 22, 2015, 03:38:57 am
I'm just trying to grasp a topic that I'm sure is possible in SFML, but I have no idea how it would be done. What I'm planning to do is create a program that would make multiple sf::RectangleShape(s) and have then individually move downward at the same time. I understand how sf::Threads are used, so my problem isn't coming from that, but I wouldn't know where to start when making a function that creates multiple objects, then moves them all individually.

Another application I hope to use this in is to create a gun that has multiple projectiles on the screen at once. But I have no idea where to start.

( Please help, I have a coding event coming up soon and I want to learn how to do this before I can feel competent enough to build a program on the fly. )
Title: Re: How to randomly create rectangles?
Post by: AlexxanderX on May 22, 2015, 07:27:05 am
From what I read you should take a good C++ book and read it. For what you want to make you don't need threads and can do everything in the main thread.
Title: Re: How to randomly create rectangles?
Post by: Hapax on May 22, 2015, 05:45:00 pm
A simple std::vector (http://www.cplusplus.com/reference/vector/vector/) of sf::Rectangles should suffice for what you are describing.
Title: Re: How to randomly create rectangles?
Post by: Jesper Juhl on May 22, 2015, 07:15:53 pm
First of all: there is absolutely no need to use threads for this. That would only complicate things greatly for no gain what-so-ever.

What you want to do is something like this (can be optimized slightly, but I tried to favor simplicity):

In your game loop (each frame):

1. Check if the current number of rectanges that you have is below the number you want to have. If it is below the wanted count, go to 2. Else go to 3.

2. While you have not yet reached the desired number of rectangles, generate a new one and place it into your container of rectangles (as Hapax said, a std::vector would be ideal).

3. For each rectangle in your container, move it downwards by an amount corresponding to its desired velocity relative to the time since last frame (delta time). If the rectangle is now outside the screen; remove it from the container.

4. Clear the screen.

5. Iterate your container and draw each rectangle.

6. Display the result.

7. Repeat from step 1 for the next frame.

Some links that may help you - read them carefully (possibly multiple times until you are sure you understand them):

On random number generation:
http://en.cppreference.com/w/cpp/numeric/random

On game loops in general:
http://www.koonsolo.com/news/dewitters-gameloop/

On achieving smooth motion:
http://gafferongames.com/game-physics/fix-your-timestep/

On general gamedev stuff:
http://www.redblobgames.com/
http://gameprogrammingpatterns.com/

I hope that helps. :)