Centering Shapes/Objects in SFML for C++ - c++

So recently, I have begun using SFML to make games in Visual Studio.
After setting everything up, and writing some sample code, I devised this:
#include <SFML/Graphics.hpp>
int main()
{
sf::RenderWindow window(sf::VideoMode(600, 600), "Move the Shape");
sf::CircleShape shape(100.f);
shape.setFillColor(sf::Color::Green);
while (window.isOpen())
{
sf::Event event;
while (window.pollEvent(event))
{
if (event.type == sf::Event::Closed)
window.close();
}
window.clear();
window.draw(shape);
window.display();
}
return 0;
}
The program produces the following result:
How do I place the circle in the center? I want to set up some code after that lets the user move the circle with the keyboard's arrow keys, so I need the circle in the center.

You need to set the position of shape with shape.setPosition(x, y). You know the width and height of the window (600px each way), and you know the radius of the circle (100px), so you can calculate the x and y that the circle needs to be moved to be centered. I'll leave that as an exercise for you.
You may also want to consider setting the origin of your circle so that you can position it by its center point (see setOrigin).

Actually, I've answered my own question. To set the position of an item, write:
shape.setPosition(x, y);

If you want to center a circle you can do something like this
circle.setPosition((window.getSize().x / 2.f) - circle.getRadius(), (window.getSize().y / 2.f) - circle.getRadius());

First, you should set the origin of the circle in the middle of it:
circle.setOrigin( circle.getRadius() / 2 , circle.getRadius() / 2 );
The, just move the center of the circle in the middle of the scree:
circle.setPosition( window.getSize().x / 2 , window.getSize().y / 2 );

Related

Changing the world origin in C++ SFML

I've recently gotten into SFML and as an exercise to get more comfortable (and have fun), I started translating some Coding Challenges done by Daniel Shiffman on his Youtube channel, The Coding Train. Upon attempting to translate a star field effect in SFML, I started searching for the right function in SFML that would change the world origin from the top-left of the screen to the center. The closest thing I found to this was the setOrigin function, but that only works for sprites and not the whole window/screen. If you didn't understand my description of this function, it would be the equivalent of the translate(x, y) function in Processing. Any help would be appreciated.
You need to use sf::View
https://www.sfml-dev.org/tutorials/2.5/graphics-view.php
Here is a small implementation example:
#include <SFML/Graphics.hpp>
int main()
{
sf::RenderWindow window(sf::VideoMode(300, 300), "");
sf::Vector2u size = window.getSize();
sf::View view(sf::Vector2f(0, 0), sf::Vector2f(size.x, size.y));
window.setView(view);
sf::CircleShape cir(10);
cir.setOrigin(10, 10);
while(window.isOpen())
{
sf::Event event;
while (window.pollEvent(event))
if (event.type == sf::Event::Closed)
window.close();
window.clear();
window.draw(cir);
window.display();
}
return 0;
}

How to know a sprite position inside a view, relative to window?

I have this sprite of a car that moves with varied speed.
It is inside a view and the view is moved to the left to keep the car always in the center of the window.
The view accompanies the displacement of the car, ie it is shifted to the left as the car accelerates or brakes.
This way the car will always appear in the center.
But if for example it is overtaken by another car, it will be left behind.
For it not to disappear from the window, I have to zoom in the view so that all the cars appear.
But for this, I need to know the position of the car in relation to the window (not in relation to the view).
getGlobalBounds().left or getPosition().x show the same value, which is the position relative to the view, not relative to the window, as shown in the image.
How to know a sprite position inside a view, relative to window?
After several hours of research, I finally find the easy way of achieve this. And yes, it was ridiculously easy.
But first, I would like to clear up some misconceptions.
getGlobalBounds().left or getPosition().x show the same value,
which is the position relative to the view, not relative to the
window, as shown in the image.
In fact, those methods return the position in the world, not in the view nor in the window.
You can have, for instance, a 500x500 window, with a 400x400 view, in a 10000x10000 world. You can place things in the world, outside of the view or the window. When the world is rendered, then the transformations of the view (translations, rotations, zoom, ...) are applied to the world and things are finally shown in the window.
To know where a coordinate in the world is represented in the window (or any other RenderTarget) and vice versa, SFML actually have a couple of functions:
RenderTarget.mapCoordsToPixel(Vector2f point)
Given a point in the world gives you the corresponding point in the RenderTarget.
RenderTarget.mapPixelToCoords(Vector2f point)
Given a point in the RenderTarget gives you the corresponding point in the world. (this is useful to map mouse clicks to corresponding points in your world)
Result
Code
int main()
{
RenderWindow window({ 500, 500 }, "SFML Views", Style::Close);
sf::View camera(sf::FloatRect(0, 0, window.getSize().x, window.getSize().y));
sf::Vector2f orig(window.getSize().x / 2, window.getSize().y / 2);
camera.setCenter(orig);
sf::Font f;
f.loadFromFile("C:/Windows/Fonts/Arial.ttf");
sf::Text t;
t.setFont(f);
sf::RectangleShape r;
r.setPosition(10, 10);
r.setSize(sf::Vector2f(20, 20));
r.setOutlineColor(sf::Color::Blue);
r.setFillColor(sf::Color::Blue);
t.setPosition(10, 40);
while (window.isOpen())
{
for (Event event; window.pollEvent(event);)
if (event.type == Event::Closed)
window.close();
else if (event.type == Event::KeyPressed){
camera.move(-3, 0);
camera.rotate(5.0);
camera.zoom(1.1);
}
auto realPos = window.mapCoordsToPixel(r.getPosition());
std::string str = "Pos: (" + std::to_string(realPos.x) +","+ std::to_string(realPos.y) + ")";
t.setString(str);
window.clear();
window.setView(camera);
window.draw(r);
window.draw(t);
window.display();
}
return EXIT_SUCCESS;
}

SFML Views setCenter vs rotation

I have a view with same dimensions of original window (500,300)
I apply view.zoom(2) to leave the view at half the size.
Now the view is centered. I want to move the view to the upper left corner of the original window. So I put view.setCenter(500,300);
The view is now correctly positioned in the upper corner of the original window. But now I want to rotate the view, making the center of the view its own top left corner, ie (0,0): view.setRotation(5);
As you can see, the center of the axis of rotation should be 0.0 but not respected.
The problem is that if I do view.setCenter (0,0), the whole view returns to the middle of the original window.
How to solve this?
Instead of using view.setCenter(500,300); move it via view.move(x_offset, y_offset);. Then applying setCenter(...) won't redefine the center and it won't get reset.
I recommend consulting the API reference of View for further reading.
You might also be interested in void sf::View::setViewport(const FloatRect& viewport) or void sf::View::reset(const FloatRect& rectangle).
This code, kindly provided by Geheim, solves the problem and also teaches a more practical approach to SFML.
#include <SFML/Graphics.hpp>
int main()
{
sf::RenderWindow window({500, 300}, "SFML Views", sf::Style::Close);
window.setFramerateLimit(120);
bool useViewPort {true}; // change this to false to see the other version
sf::View camera {{0, 0}, static_cast<sf::Vector2f>(window.getSize())};
if (useViewPort)
{
camera.setViewport({-0.5f, -0.5f, 1, 1});
camera.rotate(5);
}
else
camera.setCenter(camera.getSize());
camera.zoom(2);
window.setView(camera);
sf::RectangleShape background {camera.getSize()};
sf::RectangleShape square {{50, 50}};
square.setFillColor(sf::Color::Red);
sf::RenderTexture texture;
texture.create(window.getSize().x, window.getSize().y);
while (window.isOpen())
{
for (sf::Event event; window.pollEvent(event);)
if (event.type == sf::Event::Closed)
window.close();
window.clear();
if (useViewPort)
{
window.draw(background);
window.draw(square);
}
else
{
texture.clear();
texture.draw(background);
texture.draw(square);
texture.display();
sf::Sprite content {texture.getTexture()};
content.rotate(-5); // you have to rotate in the other disquareion here, do you know why?
window.draw(content);
}
window.display();
}
return EXIT_SUCCESS;
}
I'm glad you got the result you wanted by applying viewports using Geheim's code.
However, if you don't want to be using viewports to clip areas of the window and such, you can still rotate a view around a specific point other than its centre. You just need a little bit of mathematics...
Take the different between the target point (in the view's co-ordinate system) and the view's centre and rotate that point by the amount you wish to rotate the view and around the view's centre. Then, calculate the difference between those points (the target point and the rotated point). Once you have this difference, simply rotate the view (around its centre as normal) but then move the view by that difference.
It might sound complicated so you might want to just use this free function that I made that does it all automatically; it's on the SFML Wiki:
RotateViewAt

C++ SFML, orbiting

I recently started to learn SFML, and I have a question, how to make what would be the second body moving in an orbit, help please.
#include <SFML/Graphics.hpp>
using namespace sf;
int main()
{
RenderWindow window(VideoMode(800, 600), "Hello, world!");
CircleShape shape(50.f);
shape.setFillColor(Color::Black);
shape.setPosition(400,300);
shape.setOrigin(50,50);
CircleShape shape2(10.f);
shape2.setFillColor(Color::Black);
shape2.setPosition(700,500);
shape2.setOrigin(10,10);
while (window.isOpen())
{
Event event;
while (window.pollEvent(event))
{
if (event.type == sf::Event::Closed)
window.close();
}
window.clear(Color::White);
window.draw(shape);
window.draw(shape2);
window.display();
}
return 0;
}
Well... I will not post full solution. It would not be educational to give you complete code. But I will give you some hints :) .
Your world update should happen in the loop. In the while loop. You have two there. Which one do you think is the one which updates your world?
Circle equation in Cartesian coordinate system is: (x-a)^2 + (y-b)^2 = r^2
In the loop from 1 you should use equation from 2 to update coordinates of second object (shape2).
To perform action from point 3 you have two possibilities: function setPosition and function move, both members of class CircleShape.
If you have further questions ask them in the comments.
For your future questions on stack: give us proof that you put some effort in resolving problem. If question looks like the one I'm answering now we have the idea that you did not think about it just posted it here and you are waiting for someone to write your code for you.
The easiest and i think most precise way would be to use two perpendicular sine waves with the origin being your well origin and the amplitude being the distance for which you want to orbit.
#include <cmath> -- sin(), cos functions
As you probably know sin goes from 0 to 1 then -1 and it repeats. cos is identical but shifted. If you use both for the position then you're left with the sine and cosine values of a given number. If you use one for 'x' and the other for 'y' you're left with circular motion (perpendicular waves). Try out the code below:
int main()
{
CircleShape shape(50.f);
shape.setFillColor(Color::Black);
shape.setPosition(400,300);
shape.setOrigin(50,50);
CircleShape shape2(10.f);
shape2.setFillColor(Color::Black);
shape2.setPosition(700,500);
shape2.setOrigin(10,10);
CircleShape shape3(10.f);
shape3.setFillColor(Color::Black);
shape3.setPosition(700,500);
shape3.setOrigin(10,10);
CircleShape shape4(10.f);
shape4.setFillColor(Color::Black);
shape4.setPosition(700,500);
shape4.setOrigin(10,10);
float speed = 0.01;
float distance = 100;
// create the window
sf::RenderWindow window(sf::VideoMode(800, 600), "My window");
window.setFramerateLimit(60);
float counter = 0;
// run the program as long as the window is open
while (window.isOpen())
{
// check all the window's events that were triggered since the last iteration of the loop
sf::Event event;
while (window.pollEvent(event))
{
// "close requested" event: we close the window
if (event.type == sf::Event::Closed)
window.close();
}
counter += speed;
// clear the window with black color
window.clear(Color::White);
shape2.setPosition(shape.getPosition().x+distance*sin(counter),shape.getPosition().y+distance*cos(counter));
shape3.setPosition(shape.getPosition().x+distance*sin(counter),shape.getPosition().y+distance*sin(counter));
shape4.setPosition(shape.getPosition().x+2*distance*sin(counter),shape.getPosition().y+distance*cos(counter));
// draw everything here...
// window.draw(...);
window.draw(shape);
window.draw(shape2);
window.draw(shape3);
window.draw(shape4);
// end the current frame
window.display();
}
return 0;
}
As you can see shape2 is oribitng shape1. Shape2 and shape3's position is dependant on the position of shape1 (our origin) as well as the sine and cosine values generated. I marked distinct places in the code with variables to show you the possibilities you can have with this setup. Let's go through the setposition function:
For both x and y we need a base position from which the shape will orbit. we use shape1's position. The sine and cos need some type of number input from which to generate a value. I just used a normal iterator that grows every frame by 'speed' amount. the more it is the faster the sine will repeat thus faster orbiting around the shape1. The next part is the addition of the sine and cos values to the origin. this is where things get fun. we're essentially adding the sine value to the position to move it by that much in any direction. 'Distance' is how much we multiply the sine cos values. Thus bigger distance = further away.
Note:
using sine for x and cos for y you get a normal circular orbit.
using sine for both x and y you get a 3D-looking orbit to and from the screen (shape3)
multiplying sine and cos value additions by a non identical number will result in eliptical rotations (shape4)

Make Object Move Smoothly In C++-SFML

Hey Guys I'm a Beginner in Game Development with C++ and Sfml I Wrote this code to make that purple Object move,but the problem is that it doesn't move smoothly, it's like the text input, How to fix That ?
Here Is My code :
#include <SFML/Graphics.hpp>
int main()
{
sf::ContextSettings settings;
settings.antialiasingLevel = 12;
sf::RenderWindow window(sf::VideoMode(640, 480), "Ala Eddine", sf::Style::Default, settings);
sf::CircleShape player(20, 5);
player.setFillColor(sf::Color(150, 70, 250));
player.setOutlineThickness(4);
player.setOutlineColor(sf::Color(100, 50, 250));
player.setPosition(200, 200);
while(window.isOpen())
{
sf::Event event;
while(window.pollEvent(event))
{
if(event.type == sf::Event::Closed || sf::Keyboard::isKeyPressed(sf::Keyboard::Escape))
{
window.close();
}
//MOOVING PLAYER////////////////////////////////////////
// moving our player to the right //
if(sf::Keyboard::isKeyPressed(sf::Keyboard::D)){ //
//
//
player.move(3, 0);
}
// moving our player to the left
if(sf::Keyboard::isKeyPressed(sf::Keyboard::Q)){
player.move(-3, 0);
}
// moving our player to the UP
if(sf::Keyboard::isKeyPressed(sf::Keyboard::Z)){
player.move(0, -3);
}
// moving our player to DOWN
if(sf::Keyboard::isKeyPressed(sf::Keyboard::S)){
player.move(0, 3);
}
}
window.clear();
window.draw(player);
window.display();
}
return 0;
}
I assume your player.move() method simply adds the offset to the player position. This means that your object will always move with the same constant velocity (assuming frame rate is constant). What you want instead is to have an acceleration which updates the velocity in every frame.
Here's the basic idea (for one direction; the y direction will work accordingly, although using vectors would be better):
Give your object both a velocity and an acceleration.
If a key is held down, set the acceleration to a constant term, otherwise set it to zero.
In every frame, add timestep * acceleration to the velocity.
In every frame, add timestep * velocity to the object position.
In every frame, multiply the velocity with some decay factor, say 0.99.
This is assuming you have a fixed timestep (say, 1/60 s for 60 fps). Timestepping is slightly more advanced, and I'll refer you to this article on the topic.