Hello!
Got an weird problem where my booleans are not being set.
sf::FloatRect blockRect = levelBlocks[i].getGlobalBounds();
//Handle x axis collision
if(blockRect.intersects(playerNextX) == 1){
std::cout << "Intersects!" << std::endl;
moveX = false;
}
//Handle y axis
if(blockRect.intersects(playerNextY) == 1) {
moveY = false;
}
if (moveX) {
player.setPosition(playerNextX.left, player.getPosition().y);
}
if (moveY) {
player.setPosition(player.getPosition().x, playerNextY.top);
}
Im trying to use the code above for collison checking. The problem is that even if the code enters the intersects statement and print, thus making move false, the character moves. When printing after the intersect statement the boolean is indead always true. This is very weird as I can set the move variables just fine when listening for keyboard events.
Hopefully someone know something!
This is superwierd, the debugger says that move bool is set correctly but player still moves.
Whole game loop:
while (window.isOpen())
{
sf::Event event;
while (window.pollEvent(event))
{
if (event.type == sf::Event::Closed)
window.close();
}
//Setup for calc collision
sf::Vector2f playerPos = player.getPosition();
playerNextX.left = playerPos.x;
playerNextY.top = playerPos.y;
moveX = false;
moveY = false;
//Handle input
if (sf::Keyboard::isKeyPressed(sf::Keyboard::Left))
{
playerNextX.left -= playerSpeed;
moveX = true;
}
if (sf::Keyboard::isKeyPressed(sf::Keyboard::Right))
{
playerNextX.left += playerSpeed;
moveX = true;
}
if (sf::Keyboard::isKeyPressed(sf::Keyboard::Up))
{
playerNextY.top -= playerSpeed;
moveY = true;
}
if (sf::Keyboard::isKeyPressed(sf::Keyboard::Down))
{
playerNextY.top += playerSpeed;
moveY = true;
}
//Start graphics process
window.clear();
//Handle level logic
for (int i = 0; i < levelBlocks.size(); i++) {
sf::FloatRect blockRect = levelBlocks[i].getGlobalBounds();
//Handle x axis collision
if(blockRect.intersects(playerNextX) == 1){
std::cout << "Intersects X!" << std::endl;
moveX = false;
}
//Handle y axis
if(blockRect.intersects(playerNextY) == 1) {
std::cout << "Intersects Y!" << std::endl;
moveY = false;
}
if (moveX) {
std::cout << "MOVING X!" << std::endl;
player.setPosition(playerNextX.left, player.getPosition().y);
}
if (moveY) {
player.setPosition(player.getPosition().x, playerNextY.top);
}
//Add to draw queue
window.draw(levelBlocks[i]);
}
window.draw(player);
//Display level
window.display();
window.setFramerateLimit(30);
}
return 0;
}
Moving is also printed, despite debugger saying it does not enter if statement. Did I break C++?
Also, im noticing that blockrect.intersects is true as long as player is on the same "level", it does not actually intersect. Any ideas? Or should I try to compile on another computer maybe