在sfml中绘制多个对象时出现问题

问题描述

我想知道当我尝试绘制一个类的对象时代码有什么问题。对于我的可绘制类Box,我具有一个矩形形状和一个精灵。当我声明要在main.cpp中绘制的类的实例时,只有Box test(1,1)可以根据需要正确绘制。但是,所有其他实例,例如Box test1(2,2);盒子test2(3,3)只能绘制矩形,而不能绘制精灵。有什么方法可以修复它,以便像Box test(1,1)一样正确绘制对象Box的任何其他实例?如实例test(1,1)所示,图像已正确加载。这是我的代码

Box.h

#ifndef LINKEDLIST_TEMPLATE_Box_H
#define LINKEDLIST_TEMPLATE_Box_H


#include <SFML/Graphics.hpp>

class Box:public sf::Drawable,sf::Transformable {
protected:
    int col;
    int row;
    sf::Color color;
    sf::RectangleShape BoxBackGround;
    sf::Sprite queen;
    sf::Texture texture;
public:
  
    void draw(sf::rendertarget &window,sf::RenderStates state) const;
    int getRow();
    int getCol();
    void setRow(int row);
    void setCol(int col);
    Box(int row,int col);
    void setBox(int x,int y);
    Box();
    void setTexture();
    void setQueen();
};

Box.cpp

#include "Box.h"
int Box::getCol() {
    return col;
}
int Box::getRow() {
    return row;
}
void Box::setCol(int col) {
    this->col = col;
}
void Box::setRow(int row) {
    this->row = row;
}
Box::Box(){
    row = 0;
    col = 0;
    this->setBox(this->row,this->col);
    this->setTexture();
    this->setQueen();
}
Box::Box(int row,int col) {
    this->row = row;
    this->col = col;
    this->setBox(this->row,this->col);
    this->setTexture();
    this->setQueen();

}
void Box::setBox(int x,int y) {
    BoxBackGround.setSize({200.f,200.f});
    BoxBackGround.setFillColor(sf::Color::White);
    BoxBackGround.setPosition(x*210,y*210);
}

void Box::draw(sf::rendertarget &window,sf::RenderStates state) const {
    window.draw(BoxBackGround);
    window.draw(queen);
}
void Box::setTexture() {

    texture.loadFromFile("queen.png");
}
void Box::setQueen() {
    this->queen.setTexture(this->texture);
    this->queen.setScale(0.08f,0.08f);
    this->queen.setPosition(this->BoxBackGround.getGlobalBounds().height+50,this->BoxBackGround.getGlobalBounds().width+30);
}

main.cpp

#include "Box.h"
int main() {

    Box test(1,1);
    Box test1(2,2);
    Box test2(3,3);
    sf::RenderWindow window(sf::VideoMode(1980,1080,32),"Test");
    while(window.isopen()) {
        sf::Event event;
        while (window.pollEvent(event)) {
            if (event.type == sf::Event::Closed) {
                window.close();
            }
        }
        window.clear(sf::Color::Black);
        window.draw(test2);
        window.draw(test);
        window.draw(test1);
        window.display();
    }
return 0;
}

解决方法

void Box::setQueen

在该行中: this->queen.setPosition(this->boxBackGround.getGlobalBounds().height+50,this->boxBackGround.getGlobalBounds().width+30);

您应该将值添加到.top返回的.left的{​​{1}}和sf::Rect成员中。 getGlobalBounds().width对于每个盒子的.height将始终相同,因此在您的代码中,皇后区都在同一位置呈现。