Hello, I am writing my first SFML project today.
I write a simple class which encapsulates a CircleShape class.
Ball.h
class Ball
{
public:
Ball() = delete;
Ball(Ball &) = delete;
Ball( const std::string & texturePath,
const float radius,
const float initialX,
const float initialY,
const float initialVX,
const float initialVY,
const float initialR,
const float initialWR);
sf::CircleShape shape;
void Update();
private:
float radius;
float x, y;
float vx, vy;
float theta, w;
sf::Texture texture;
std::chrono::time_point<std::chrono::steady_clock> lastUpdate;
};
Ball.cpp
#include "Ball.h"
Ball::Ball( const std::string & texturePath,
const float radius,
const float initialX,
const float initialY,
const float initialVX,
const float initialVY,
const float initialR,
const float initialWR)
: texture ()
, radius (radius)
, x (initialX)
, y (initialY)
, vx (initialVX)
, vy (initialVY)
, theta (initialR)
, w (initialWR)
, shape (radius)
, lastUpdate (std::chrono::steady_clock::now())
{
texture.loadFromFile(texturePath);
shape.setTexture(&texture, false);
//shape.setOrigin(x - radius / 2.0f, y - radius / 2.0f);
shape.setFillColor(sf::Color::Green);
Update();
}
void Ball::Update()
{
std::chrono::time_point<std::chrono::steady_clock> now = std::chrono::steady_clock::now();
const float dt = std::chrono::duration_cast<std::chrono::duration<float>>(lastUpdate - now).count();
lastUpdate = now;
theta += w * dt;
x += vx * dt;
y += vy * dt;
shape.setRotation(theta);
shape.setPosition(x, y);
}
main.cpp
#include "Ball.h"
#include <SFML/Graphics.hpp>
int main()
{
Ball mehmet("resources/Cavus.png",
50.0f,
400, 400,
0, 0,
0, 10.0);
sf::RenderWindow window(sf::VideoMode(800, 800), "SFML works!");
while (window.isOpen())
{
sf::Event event;
while (window.pollEvent(event))
{
if (event.type == sf::Event::Closed)
window.close();
}
mehmet.Update();
window.clear();
window.draw(mehmet.shape);
window.display();
}
return EXIT_SUCCESS;
}
I want to create a Ball object. I give it an initial position, velocity, rotation and angular velocity. I update the dynamics of the object by using the Update() method.
When I call the setRotation() method, it indeed rotates the Ball, but the pivot point is the upper left corner of the initial rectangular bounding box of the Ball. I found the setOrigin() method in the documentation. setOrigin() is said to change the origin of the object. I set it to the center of the ball in the constructor as seen in my code. But when I use it like that, I cannot change the position of my ball anymore.
What am I missing here? I simply want to rotate and move round object. Can you please guide me?
Thanks in advance.