2
« on: September 02, 2011, 05:36:59 pm »
I'm trying to create a very simple Pong game on my own before I get into anything more complex. However, I can't seem to get the ball to bounce off of the sides of the screen. No matter what I've tried, it just goes offscreen every time. Can anyone help a noob out? The ball is 20x20px so I wanted it to bounce when its center is within 20 units of the edge of the screen. In the code below I've only (unsuccessfully) implemented a bounce for when it goes past the y-maximum as that is where it goes by default in the example so far.
////////////////////////////////////////////////////////////
// Headers
////////////////////////////////////////////////////////////
#include <SFML/Graphics.hpp>
////////////////////////////////////////////////////////////
/// Entry point of application
///
/// \return Application exit code
///
////////////////////////////////////////////////////////////
int main()
{
// Create main window
srand ( time(NULL) );
sf::RenderWindow App(sf::VideoMode(640, 480), "Pong");
sf::Image playerimg;
if (!playerimg.LoadFromFile("paddle.png"))
{
// Error...
}
sf::Image computerimg;
if (!computerimg.LoadFromFile("paddle.png"))
{
// Error...
}
sf::Image ballimg;
if (!ballimg.LoadFromFile("ball.png"))
{
// Error...
}
int ball_x=300;
int ball_y=220;
int ball_start = 2;
int ball_count = 1;
sf::Sprite player;
sf::Sprite computer;
sf::Sprite ball;
player.SetImage(playerimg);
computer.SetImage(computerimg);
ball.SetImage(ballimg);
player.SetPosition(0,160);
computer.SetPosition(625,160);
ball.SetPosition(ball_x,ball_y);
bool ballIsVisible = true;
if (ball.GetPosition().y > 460) {
ballIsVisible == false;
}
// Start game loop
while (App.IsOpened())
{
// Process events
sf::Event Event;
while (App.GetEvent(Event))
{
// Close window : exit
if (Event.Type == sf::Event::Closed)
App.Close();
}
float ElapsedTime = App.GetFrameTime();
if (App.GetInput().IsKeyDown(sf::Key::Up)) player.Move(0, -100 * ElapsedTime);
if (App.GetInput().IsKeyDown(sf::Key::Down)) player.Move(0, 100 * ElapsedTime);
if (ball_start==2) ball.Move(150 * ElapsedTime, 150 * ElapsedTime);
if (ballIsVisible==false) ball.Move((-1 * (150 * ElapsedTime)), (-1 * (150 * ElapsedTime)));
App.Clear();
App.Draw(player);
App.Draw(ball);
App.Draw(computer);
App.Display();
}
return EXIT_SUCCESS;
}