Hi! I'm trying to make a game, but on different computers the speed of the ball is different. I know I have to use the sf::Clock but I don't know how?
Can you help me?
#include <SFML/Graphics.hpp>
#include <vector>
#include <iostream>
#include <ctime>
#include <cstdlib>
#include <string>
#include <sstream>
std::string convertInt(int number)
{
std::stringstream ss;
ss << number;
return ss.str();
}
const float speed = 0.3;
int main(int argc, char** argv)
{
sf::RenderWindow window(sf::VideoMode(800, 800), "Bounce!!!");
int nr = 0;
sf::Font font;
if(!font.loadFromFile("arial.ttf"))
return -1;
std::vector<float> random_neg;
std::vector<float> random_pos;
random_neg.push_back(-0.3);
random_neg.push_back(-0.2);
random_pos.push_back(0.2);
random_pos.push_back(0.3);
float x1 = -0.2, y1 = -0.3;
srand(time(0));
int random1 = rand() % 2;
int random2 = rand() % 2;
sf::RectangleShape paddle;
paddle.setFillColor(sf::Color::Blue);
paddle.setPosition(350, 650);
paddle.setSize(sf::Vector2f(100, 10));
sf::CircleShape ball;
ball.setRadius(10);
ball.setPosition(335, 335);
ball.setFillColor(sf::Color::Red);
window.setMouseCursorVisible(false);
while(window.isOpen())
{
sf::Event event;
while(window.pollEvent(event))
{
switch(event.type)
{
case sf::Event::Closed:
window.close();
break;
case sf::Event::KeyPressed:
if(event.key.code == sf::Keyboard::Escape)
window.close();
break;
}
}
paddle.setPosition(sf::Mouse::getPosition(window).x, 650);
if(paddle.getPosition().x <= 0)
paddle.setPosition(0, 650);
if(paddle.getPosition().x >= 700)
paddle.setPosition(700, 650);
if(ball.getPosition().y <= 0)
{
random1 = rand() % 2;
y1 = random_pos[random1];
}
if(ball.getPosition().y >= 785)
{
random1 = rand() % 2;
y1 = random_neg[random1];
}
if(ball.getPosition().x <= 0)
{
random1 = rand() % 2;
x1 = random_pos[random2];
}
if(ball.getPosition().x >= 800)
{
random1 = rand() % 2;
x1 = random_neg[random2];
}
if( ball.getPosition().x <= paddle.getPosition().x + 100 &&
ball.getPosition().x >= paddle.getPosition().x - 40 &&
ball.getPosition().y <= paddle.getPosition().y + 10 &&
ball.getPosition().y >= paddle.getPosition().y - 10 )
{
++nr;
y1 = random_neg[random1];
if(x1 < 0)
x1 = random_neg[random2];
else
x1 = random_pos[random2];
ball.move(x1, y1);
}
else
ball.move(x1, y1);
if(ball.getPosition().y >= 650)
{
ball.setPosition(300, 300);
break;
}
std::string score0 = "Score: " + convertInt(nr);
sf::Text score;
score.setString(score0);
score.setFont(font);
score.setCharacterSize(15);
score.setPosition(700, 750);
score.setColor(sf::Color::Black);
window.clear(sf::Color::Yellow);
window.draw(paddle);
window.draw(ball);
window.draw(score);
window.display();
}
}