Making pong clone in sfml as first project, ball not randomly moving

Ok, so I am a beginner in c++ and I am using sfml 2.2 to make a game using the IDE Code Blocks. I still have a lot to go, but here is the code I have (I am making the ball first)

Main.cpp:

#include "Ball.hpp"
#include <SFML/Graphics.hpp>
#include <stdlib.h>
#include <math.h>
int main()
{
sf::ContextSettings settings; //this will make a settings to change
settings.antialiasingLevel = 8; //make shapes smooth

sf::RenderWindow window(sf::VideoMode(600, 500), "Ryan's Pong Clone in c++", sf::Style::Titlebar | sf::Style::Close, settings);
window.setFramerateLimit(20);
//set up the ball
Ball mainBall; //ball used for the rest of the game
mainBall.x = 600 / 2; //set x position of the to the middle of the screen
mainBall.y = 500 / 2; //set y position of the to the middle of the screen
mainBall.headingTo = rand() % 359; //set a random place for the ball to go
mainBall.speed = 0.01; //this will always be the same, but it will allow new features in the future and will help in debugging without rewriting large amounts of code
sf::CircleShape Ball(10); //make our circle shape for the ball
Ball.setPosition(mainBall.x, mainBall.y); //set position of the ball
Ball.setFillColor(sf::Color(255, 255, 255)); //make ball white

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

window.clear(); //clear the window

//game loop in here
mainBall.x = mainBall.x + cos (mainBall.headingTo) * mainBall.speed;
mainBall.y = mainBall.y + sin (mainBall.headingTo) * mainBall.speed;

Ball.setPosition(mainBall.x, mainBall.y);

window.draw(Ball);

window.display(); //End current frame
}

return 0;
}

Ball.hpp:

#include <SFML/Graphics.hpp>

class Ball {
public:
int x; //x position of ball
int y; //y position of ball
int headingTo; //where the ball is heading to degrees
double speed; //speed of the ball
private:

The code compiles without problem, but when I run it the program does not act as expected. The ball always goes to the top left corner, even though I have a random number. Is this a problem with the random number or am I not using cos and sin correctly, or is it something completely different. Also, if possible, a review of my code would be great.
You have to call srand(time(NULL)) once at the start of your program to seed the generator, otherwise it will always start at the same seed.

By the way, you should not use rand() or related functions as it is becoming deprecated. Favor instead the new random classes added in C++11 in the <random> header:
http://www.cplusplus.com/reference/random/
http://en.cppreference.com/w/cpp/header/random
Last edited on
Topic archived. No new replies allowed.