Hi all, I'm relatively new to programming and brand new to using external libraries/game design. I'm slowly working through the tutorials to get an idea for what I can do.
I know the theory behind the white square problem, but I've run into a problem. Below are two sets of code; the first runs fine but the second (which was my practice to replicate the program slightly differently) displays white squares. I'm not sure where scoping is different between the two or if it's something else causing the issue.
Code 1 (not working)
int main()
{
// Create Window
sf::RenderWindow window;
window.create(sf::VideoMode(1280, 640), "Window");
sf::Texture SpritesTexture;
if (!LoadTexture(SpritesTexture, "Sprites/sprites.png"))
std::cout << "Failed to load texture\n";
sf::Sprite ground1;
ground1.setTexture(SpritesTexture);
ground1.setTextureRect(sf::IntRect(0, 0, 128, 128));
ground1.setPosition(10, 10);
sf::Sprite ground2;
ground2.setTexture(SpritesTexture);
ground2.setTextureRect(sf::IntRect(128, 0, 128, 128));
ground2.setPosition(138, 10);
while (window.isOpen())
{
sf::Event event;
while (window.pollEvent(event))
{
if (event.type == sf::Event::Closed)
{
window.close();
break;
}
}
window.clear(sf::Color::Black);
window.draw(ground1);
window.draw(ground2);
window.display();
}
return 0;
}
Code 2 (working)
int main()
{
//////// Create Window
sf::RenderWindow window;
window.create(sf::VideoMode(800, 600), "Window");
/////// Create Sprite
// Create texture
sf::Texture texture;
if (!texture.loadFromFile("Sprites/Happy_Mask_Salesman's_Piano.png"))
{
std::cout << "Error: Couldn't load texture\n";
}
// Load texture onto sprites
sf::Sprite character;
character.setTexture(texture);
character.setTextureRect(sf::IntRect(32, 32, 128, 128));
sf::Sprite rock;
rock.setTexture(texture);
rock.setTextureRect(sf::IntRect(128, 128, 128, 128));
rock.setPosition(200, 200);
/////// Main Loop
while (window.isOpen())
{
// Check for keyboard input
sf::Event event;
while (window.pollEvent(event))
{
// Check for event type and close OR move sprite
switch (event.type)
{
case sf::Event::Closed:
window.close();
break;
case sf::Event::KeyPressed:
// Check for type of key and update position
bool collision = character.getGlobalBounds().intersects(rock.getGlobalBounds());
if (!collision)
{
std::cout << "no collision\n";
if (sf::Keyboard::isKeyPressed(sf::Keyboard::Left))
character.move(-5.f, 0.f);
else if (sf::Keyboard::isKeyPressed(sf::Keyboard::Right))
character.move(5.f, 0.f);
else if (sf::Keyboard::isKeyPressed(sf::Keyboard::Up))
character.move(0.f, -5.f);
else if (sf::Keyboard::isKeyPressed(sf::Keyboard::Down))
character.move(0.f, 5.f);
}
else std::cout << "collision\n";
}
}
// Clear+Draw to screen
window.clear(sf::Color::Black);
window.draw(character);
window.draw(rock);
window.display();
}
return 0;
}
Apologies for the scrub code; thanks for the help!