模型类
class spaceshipModel {
private:
Vector2f position;
float speed, acceleration, energy, fuel;
public:
//Contructor
spaceshipModel() : position(0, 0), speed(0), acceleration(0), energy(0), fuel(0) {}
//Destructor
~spaceshipModel() {}
//Sets
void setPosition(float _x, float _y) { position.x = _x; position.y = _y; }
void setSpeed(float _speed) { speed = _speed; }
void setAcceleration(float _acceleration) { acceleration = _acceleration; }
void setEnergy(float _energy) { energy = _energy; }
void setFuel(float _fuel) { fuel = _fuel; }
//Gets
Vector2f getPosition() { return position; }
float getSpeed() { return speed; }
float getAcceleration() { return acceleration; }
float getEnergy() { return energy; }
float getFuel() { return fuel; }
};
查看类(class)
class spaceshipView {
private:
Texture* image;
Sprite sprite;
spaceshipModel model;
public:
//Constructor
spaceshipView() : image(0) {}
//Destructor
~spaceshipView() {}
//Setting the image
void setImage(Texture* _image) { image = _image; }
//Drawing the image
void drawImage(RenderWindow* _window) {
sprite.setTexture(*image);
sprite.setPosition(model.getPosition());
sprite.setScale(Vector2f(0.2f, 0.2f));
_window->draw(sprite);
_window->display();
}
};
主要
剩下了很多代码,但是我在main中称呼它:
int main() {
//Call instance of the Spaceship model
spaceshipModel shipModel;
//Call instance of the Spaceship view
spaceshipView shipView;
//Create the texture of the spaceship from file
Texture spaceship;
spaceship.loadFromFile("spaceship.png");
//Create the window
RenderWindow window(VideoMode(800, 600), "Spaceship with MVC");
//Run the program as long as the window is open
while (window.isOpen()) {
//Check all the window's events that were triggered since the last iteration of the loop
Event event;
while (window.pollEvent(event)) {
//"Close requested" event: we close the window
switch (event.type) {
//Window closed by pressing the X
case Event::Closed:
window.close();
break;
//Checking for key pressed event
case Event::KeyPressed:
//Pressing esc to close the window
if (event.key.code == Keyboard::Escape) {
window.close();
}
break;
//We don't process other types of events
default:
break;
}
//Clear screen with white BG
window.clear(Color::White);
//TESTING THE SETTING OF THE POSITION
std::cout << shipModel.getPosition().x << ", " << shipModel.getPosition().y << std::endl;
shipModel.setPosition(100, 100);
std::cout << shipModel.getPosition().x << ", " << shipModel.getPosition().y << std::endl;
//Set and draw the image
shipView.setImage(&spaceship);
shipView.drawImage(&window);
}
}
return 0;
}
spaceship 完美绘制,但仅设置为(0,0)。如上图所示,即使将位置设置为(100,100)。图像停留在(0,0)。由于我正在使用View类中Model类的getPosition函数,因此即使cout测试确实显示了更改,我也不认为数据正在正确更新。
我究竟做错了什么?有人可以给我一些指示吗?
最佳答案
在上面的代码段中,shipModel
和main()
中的shipView.model
对象是两个不同的对象。您可以使用shipView
中的setter来让spaceshipView
知道模型,也可以直接调用shipView.model
的方法。