I am having a problem drawing both a texture and the ball in my Pong game. When I don't load something into the texture and draw the ball, it will work. If I load something into the texture but don't draw the ball, it still works. But if I try to do them both, it'll crash after I close the window and the program is exiting. I have all my linking right and the image for the texture is in the right place.
Here's my code:
main.cpp
#include <SFML/Graphics.hpp>
#include "include/Ball.hpp"
int main()
{
//Create the main window
sf::RenderWindow main_window(sf::VideoMode(950, 600), "Epicyoobed Pong");
main_window.setKeyRepeatEnabled(false);
main_window.setFramerateLimit(60);
//Load the background
sf::Texture background_tex;
if(!background_tex.loadFromFile("background.png"))
return EXIT_FAILURE;
sf::Sprite background(background_tex);
//Create the ball
pong::Ball main_ball(sf::Vector2f(50, 50));
//Create the stuff for frame tracking
sf::Clock delta_clock;
sf::Time delta_time;
//Start the game loop
while (main_window.isOpen())
{
//Update the delta
delta_time = delta_clock.getElapsedTime();
delta_clock.restart();
//Process events
sf::Event event;
while(main_window.pollEvent(event))
{
if(event.type == sf::Event::Closed)
main_window.close();
}
//Logic
main_ball.ScreenCollide(main_window);
main_ball.update(delta_time);
//Render
main_window.clear();
main_window.draw(background);
main_window.draw(main_ball);
main_window.display();
}
return EXIT_SUCCESS;
}
Ball.hpp
#ifndef BALL_HPP
#define BALL_HPP
#include <SFML/Graphics.hpp>
namespace pong
{
class Ball : public sf::Drawable
{
public:
Ball();
Ball(sf::Vector2f start_pos);
~Ball();
//Setters
void setVelocity(sf::Vector2f new_vel);
//Collision Handling
void ScreenCollide(const sf::RenderWindow& screen);
//Main loop methods
void update(const sf::Time& dt);
void draw(sf::RenderTarget& target, sf::RenderStates states) const;
private:
//Position and velocity of the ball
sf::Vector2f m_pos = {0, 0};
sf::Vector2f m_vel = {500, 500};
//The visual representation
sf::CircleShape m_circle;
};
}
#endif // BALL_HPP
Ball.cpp
#include "../include/Ball.hpp"
#include <iostream>
namespace pong
{
Ball::Ball() = default;
Ball::Ball(sf::Vector2f start_pos) : m_pos(start_pos), m_circle(15) { m_circle.setFillColor(sf::Color::Blue); }
Ball::~Ball() = default;
void Ball::setVelocity(sf::Vector2f new_vel) { m_vel = new_vel; }
void Ball::ScreenCollide(const sf::RenderWindow& screen)
{
if(m_pos.x < 0 || (m_pos.x > screen.getSize().x - m_circle.getRadius() * 2))
m_vel.x = -m_vel.x;
if(m_pos.y < 0 || (m_pos.y > screen.getSize().y - m_circle.getRadius() * 2))
m_vel.y = -m_vel.y;
}
void Ball::update(const sf::Time& dt) { m_circle.setPosition(m_pos += (m_vel * dt.asSeconds())); }
void Ball::draw(sf::RenderTarget& target, sf::RenderStates states) const { target.draw(m_circle, states); }
}
I am on Windows 7 with with the TDM MinGW 4.8.1 and I'm using CB as my IDE.