我想知道当我尝试绘制一个类的对象时代码有什么问题。对于我的可绘制类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;
}
答案 0 :(得分: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
将始终相同,因此在您的代码中,皇后区都在同一位置呈现。