I have fixed it, I needed to set the origin for the sprite.Hello, I have found some code that implements gravity and tried to do it with a sprite (the other code used shapes), it works fine while using shapes but not when using a texture, the sprite doesnt go on top of the floor, it places itself underneath it.
Here's the code I based mine off -
https://github.com/eXpl0it3r/Examples/blob/master/SFML/SimpleAABB.cpp And here's mine:
int main()
{
//WINDOW
sf::RenderWindow window(sf::VideoMode(800, 600), "Gravity");
window.setFramerateLimit(60);
//FRAMETIME
sf::Clock frametime;
//PLAYER DATA
enum playerDirection{ Left, Right };
sf::Vector2i playerPosition(600 - 32, 350 - 32);
sf::Vector2i playerSource(1, Right);
sf::Vector2f playerSpeed(0.f, 0.f);
//GRAVITY
const float gravity = 980.f;
//COLLISION
bool inAir = true;
//SHAPES
sf::RectangleShape floor(sf::Vector2f(800.f, 40.f));
floor.setPosition(0.f, 560.f);
floor.setFillColor(sf::Color(10, 180, 30));
//TEXTURES
sf::Texture playerTexture;
if(!playerTexture.loadFromFile("playerTexture.png"))
std::cout << "Texture Error" << std::endl;
//SPRITES
sf::Sprite player;
player.setTexture(playerTexture);
player.setPosition(playerPosition.x, playerPosition.y);
player.setTextureRect(sf::IntRect(playerSource.x * 32, playerSource.y * 32, 32, 32));
//GAME LOOP
while (window.isOpen())
{
float dt = frametime.restart().asSeconds();
sf::Event event;
while (window.pollEvent(event))
{
if (event.type == sf::Event::Closed)
window.close();
}
//SLOW HORIZONTAL SPEED
if(playerSpeed.x > 6.f)
playerSpeed.x -= 5.f;
else if(playerSpeed.x < -6.f)
playerSpeed.x += 5.f;
else
playerSpeed.x = 0.f;
//ADJUST VERTICLAL SPEED
if(!inAir)
playerSpeed.y = gravity;
else if(playerSpeed.y < gravity)
playerSpeed.y += 10.f;
else if(playerSpeed.y > gravity)
playerSpeed.y = gravity;
//HORIZONTAL MOVEMENT
if(sf::Keyboard::isKeyPressed(sf::Keyboard::A) && sf::Keyboard::isKeyPressed(sf::Keyboard::D))
playerSpeed.x = 0.f;
else if(sf::Keyboard::isKeyPressed(sf::Keyboard::D)) //Move Right
playerSpeed.x = 120.f;
else if(sf::Keyboard::isKeyPressed(sf::Keyboard::A)) //Move Left
playerSpeed.x = -120.f;
//JUMPING
if(sf::Keyboard::isKeyPressed(sf::Keyboard::Space) && !inAir)
playerSpeed.y = -300.f;
//MOVE PLAYER
player.setPosition(player.getPosition().x + playerSpeed.x * dt, player.getPosition().y + playerSpeed.y * dt);
//CHECK COLLISION
if(floor.getGlobalBounds().intersects(player.getGlobalBounds()))
{
player.setPosition(player.getPosition().x, floor.getPosition().y - player.getOrigin().y);
inAir = false;
}
else
inAir = true;
//RENDER
window.clear();
window.draw(player);
window.draw(floor);
window.display();
}
return 0;
}