Can somebody tell me if there is something wrong with my code?
// Ball.hpp
#ifndef BALL_HEADER
#define BALL_HEADER
#include <SFML/Graphics.hpp>
class Ball {
public:
Ball();
~Ball();
void Update(float ElapsedTime);
void ChangeX();
void ChangeY();
void Draw(sf::RenderWindow &cWin);
float GetX() const { return X; }
float GetY() const { return Y; }
private:
sf::Shape cBall;
float X;
float XSpeed;
float Y;
float YSpeed;
};
#endif
//Ball.cpp
#include "Ball.hpp"
#include <iostream>
Ball::Ball(): X(0.0f), XSpeed(50.0f), Y(0.0f), YSpeed(50.0f) {
cBall = sf::Shape::Circle(100, 100, 10, sf::Color(100, 100, 100));
}
Ball::~Ball() {
}
void Ball::Update(float ElapsedTime) {
cBall.Move(XSpeed * ElapsedTime, YSpeed * ElapsedTime);
sf::Vector2f Pos = cBall.GetPosition();
X = Pos.x;
Y = Pos.y;
std::cout << X << " " << Y << " - " << XSpeed << " " << YSpeed << std::endl;
}
void Ball::ChangeX() {
XSpeed *= -1.0f;
}
void Ball::ChangeY() {
YSpeed *= -1.0f;
}
void Ball::Draw(sf::RenderWindow &cWin) {
cWin.Draw(cBall);
}
// Main.cpp
#include "Ball.hpp"
int main() {
sf::RenderWindow cWin(sf::VideoMode(800, 600), "test");
cWin.SetFramerateLimit(60);
sf::Event Event;
Ball cBall;
while ( cWin.IsOpened() ) {
while ( cWin.GetEvent(Event) ) {
if ( Event.Type == sf::Event::Closed )
cWin.Close();
}
cBall.Update(cWin.GetFrameTime());
if ( cBall.GetX() > 780.0f || cBall.GetX() < 20.0f )
cBall.ChangeX();
if ( cBall.GetY() > 580.0f || cBall.GetY() < 20.0f )
cBall.ChangeY();
cBall.Draw(cWin);
cWin.Display();
cWin.Clear();
}
return 0;
}
It compiles and runs. But it runs wierd.
The ball moves +50 on X and +50 on Y the first frame, then it goes -50, -50 on the next frame and repeats until I click the window and hold for 2-3 secs, then when I let go, the ball starts moving. Although the coordinates printed in the console seem fine, the ball is render off by some pixels. Also, the limits are off, everything is off!
I searched the forum for some time now, I couldn't find anything relevant. So I decided to make a new post.
Sorry for my bad English, hopefully everybody understands what I'm saying.