Search code examples
c++sfml

Offsetting a texture


I'm making a space invader clone, and while generating the the bullet texture it comes out from the ships upper edge. Here's snippets of my code:

class Bullet{
public:
    sf::Sprite shape;

    Bullet(sf::Texture *texture, sf::Vector2f pos){
        this->shape.setTexture(*texture);
        this->shape.setScale(3,3);
        this->shape.setPosition(pos);
    }

    ~Bullet() {}

};

And:

if(sf::Keyboard::isKeyPressed(sf::Keyboard::Space) && shottime >= 20){
            player.bullets.push_back(Bullet(&bt,player.shape.getPosition()));
            shottime=0;
            sound2.play();
        }

Now, I'm not quite sure how to modify this code to make the bullets come out from the middle of the ship".


Solution

  • Image/texture coordinates are usually (but not always) referencing the top left corner as the origin, and then sized by either a bottom right coordinate, or a height and width from that initial offset.

    This line will give you that top left offset: player.shape.getPosition()

    So, you should modify it to do something like this to center the bullet with the texture:

    sf::Vector2f center_pos = player.shape.getPosition();
    center_pos.x += player.shape.width() / 2;
    player.bullets.push_back(Bullet(&bt, center_pos));
    

    Of course, this assumes there is a width() function, or something similar.