I am making an asteroids-like game, with the spaceship as a basic triangle shape, and the asteroids (obviously) are circular. I have already made the spaceship class by inheriting from sf::Sprite, but I want to inherit from sf::CircleShape for the asteroids so that I can use triangle-circle collision. I could also have a circle shape as a member of the class, but then I would have to move the circle shape every time I moved the asteroid, and I think this would be simpler. Here is my code so far:
Asteroid.h:
#include <SFML\Graphics.hpp>
class Asteroid : public sf::CircleShape {
public:
Asteroid(int radius);
private:
sf::Texture _texture;
};
Asteroid.cpp:
#include "Asteroid.h"
Asteroid::Asteroid(int radius) : sf::CircleShape(radius) {
_texture.loadFromFile("images\\asteroid.png");
setTexture(&_texture);
setTextureRect(sf::IntRect(0, 0, 20, 20));
setOrigin(getRadius() / 2, getRadius() / 2);
}
main.cpp:
#include <SFML/Graphics.hpp>
#include <iostream>
#include "Spaceship.h"
#include "Asteroid.h"
using namespace std;
const int WIDTH = 720;
const int HEIGHT = 680;
sf::RenderWindow window;
int main() {
window.create(sf::VideoMode(WIDTH, HEIGHT, 32), "Asteroids!", sf::Style::Titlebar | sf::Style::Close);
Spaceship spaceship;
Asteroid asteroid(10);
sf::Event event;
while (window.isOpen()) {
while (window.pollEvent(event)) {
switch (event.type) {
case sf::Event::Closed: {
window.close();
break;
}
default:
break;
}
}
if (sf::Keyboard::isKeyPressed(sf::Keyboard::Up) || sf::Keyboard::isKeyPressed(sf::Keyboard::Down))
if (sf::Keyboard::isKeyPressed(sf::Keyboard::Up))
spaceship.speedY = -5;
else
spaceship.speedY = 5;
else
spaceship.speedY = 0;
if (sf::Keyboard::isKeyPressed(sf::Keyboard::Left) || sf::Keyboard::isKeyPressed(sf::Keyboard::Right))
if (sf::Keyboard::isKeyPressed(sf::Keyboard::Left))
spaceship.speedX = -5;
else
spaceship.speedX = 5;
else
spaceship.speedX = 0;
spaceship.move(spaceship.speedX, spaceship.speedY);
window.clear();
window.draw(asteroid);
window.draw(spaceship);
window.display();
sf::sleep(sf::milliseconds(10));
}
return 0;
}
The Asteroid header and implementation files are quite simple, as I ran into the problem fairly early on. I can't get the Asteroid to draw on the screen. "window.draw(asteroid);" gives no errors, but the asteroid image does not display on the screen.
Any help would be appreciated.