I'm a beginner at this.
I was trying out a function where it would draw a certain section of an image depending on the parameters, but if I use the function, the entire program becomes very laggy. The code is probably poorly "designed".
This is the relevant code:
void drawSolidObject(sf::Texture& buildingsTexture, int objectType, int objectNumber, float objectX, float objectY)
{
if(objectType == Building)
{
if(objectNumber == 0)
{
if(!buildingsTexture.loadFromFile("images/map/buildings.png"))
std::cout << "Error: Game failed to load 'buildings' image." << std::endl;
buildings.setTexture(buildingsTexture);
buildings.setTextureRect(sf::IntRect(0, 0, 140, 122));
buildings.setPosition(objectX, objectY);
float left = buildings.getGlobalBounds().left - 16;
float right = left + buildings.getGlobalBounds().width + 8;
float top = buildings.getGlobalBounds().top - 24;
float bottom = top + buildings.getGlobalBounds().height - 8;
sf::Vector2f newSolidObjectLF(left, right);
sf::Vector2f newSolidObjectTB(top, bottom);
if(player.getPosition().x > newSolidObjectLF.x && player.getPosition().x < newSolidObjectLF.y && player.getPosition().y > newSolidObjectTB.x && player.getPosition().y < newSolidObjectTB.y)
{
player.setPosition(prevPlayerPos.x, prevPlayerPos.y);
}
}
}
}
while(Window.isOpen())
{
drawSolidObject(House3, Building, 0, 800, 800);
}
Any suggestions to prevent the lag and use the same concept?
Thanks. Doing that removed the lag.
However, if I do this:
while(Window.isOpen())
{
drawSolidObject(House3, Building, 0, 800, 800);
drawSolidObject(House4, Building, 0, 1100, 800);
}
How do I make it so that it would show two images (House3 and House4) instead of just moving the first image (House3) to another position (1100,800)?
Because with my current code, it just moves the position of the first drawSolidObject to (1100, 800).
You have two options:
- window.draw() before drawing the second,
- create two sprites and modify them separately, then draw them together (much better)
It looks like you create a sprite called buildings. I'd suggest considering creating a vector of sprites called buildings, thusly:
std::vector<sf::Sprite> buildings;
For more information on vectors, see here (http://www.cplusplus.com/reference/vector/vector/).