I am seriously at a loss of words. I've been sitting in front of the computer trying to figure out why this is not working. I am trying to disable the player to have the ability to jump while in the air. But for some reason the player can still double jump, meanwhile if the player tries to jump a third time or a fourth time etcetera. it wont and my code works. But why am I still being able to double jump? I can not figure this out. All help is appreciated.
#include "pch.h"
#include <iostream>
#include <SFML/Graphics.hpp>
#include <SFML/Window.hpp>
using namespace std;
int width = 800;
int height = 600;
int main()
{
sf::RenderWindow window(sf::VideoMode(width, height), "In Development");
window.setFramerateLimit(70);
window.setVerticalSyncEnabled(true);
sf::RectangleShape player;
player.setSize(sf::Vector2f(50, 50));
player.setFillColor(sf::Color::Cyan);
player.setPosition(width / 2, 0);
sf::Vector2f velocity(0, 0);
float gravity = .1;
bool jumping = true;
sf::Event event;
while (window.isOpen())
{
while (window.pollEvent(event))
{
if (event.type == sf::Event::Closed)
window.close();
if (event.type == sf::Event::KeyPressed)
{
if (event.key.code == sf::Keyboard::Space)
{
if (jumping == false)
{
velocity.y = -3.5;
jumping = true;
}
}
}
}
//Gravity
if (player.getPosition().y < height / 2)
{
velocity.y += gravity;
}
else if (player.getPosition().y >= height / 2)
{
player.setPosition(player.getPosition().x, height / 2);
jumping = false;
}
//Move the player
player.move(velocity);
window.clear(sf::Color::White); //Clear
window.draw(player);
window.display(); //Display
}
int pause; cin >> pause; //Pause the program
return 0;
}
This may or may not be an appropriate place for this question. (Maybe gamedev.stackexchange.com?)
However, it looks to me like your problem is the order in which you're doing things.
In the "else if" of your gravity section, you're setting jumping
back to false if your player has reached a certain vertical position. However, you're only moving the player later in the code. So when the player jumps, jumping
gets set to true, but then immediately gets set to false again because they haven't moved yet (they're still on the ground).
Put your check for vertical position after player.move()
.