I don't see the animation of the sprite - c++

This is code after includes:
Sprite player;
Texture playerTexture;
IntRect playerContainer(0, 0, 32, 32);
Vector2f playerPosition;
int playerDirection = 0; // 0 - fwd, 1 - back, 2 - stay
This is animation update method:
void updateAnims(Clock clock, float time) {
if(time > 0.3f) {
if(playerDirection == 0) playerContainer.top = 0;
else if(playerDirection == 1) playerContainer.top = 32;
else if(playerDirection == 2) playerContainer.top = 64;
if(playerContainer.left == 96) playerContainer.left = 0;
else playerContainer.left += 32;
player.setTextureRect(playerContainer);
clock.restart();
}
}
and this method is updated in "int main()" method.
int main() {
// Init window
RenderWindow window(VideoMode(800, 600), "RPG");
Clock gameClock;
Clock animClock;
float gameTime;
float animTime;
// Setting up the player
playerTexture.loadFromFile("player.png");
player.setTexture(playerTexture);
player.setTextureRect(playerContainer);
player.setScale(Vector2f(3.f, 3.f));
playerPosition.x = 30;
playerPosition.y = 120;
player.setPosition(playerPosition);
while(window.isOpen()) {
Event event;
while(window.pollEvent(event)) {
if(event.type == Event::Closed) {
window.close();
}
}
checkInputs(gameTime);
animTime = animClock.getElapsedTime().asSeconds();
updateAnims(animClock, animTime);
window.clear();
gameTime = gameClock.getElapsedTime().asMilliseconds();
gameClock.restart();
window.display();
}
return 0;
}
Turns out that sprite is created in main method, gets texture and texture shape, gets position, but not drawn. Why?
I think think the problem is in animation method but I tried different variations of solutions.

You should call window.draw(player) method between window.clear() and window.display() to actually draw player sprite on screen.

Related

sfml gravity clipping shapes through floor

I tried to make a cube that moves side to side and bounces off the floor.
It bounced a couple times and then fell through the floor.
I tried making the floor higher.
I tried adding extra vertical velocity.
I have tried everything i can think of.
I would like to get the cube to not fall through the floor.
how do I do that?
#include <SFML/Graphics.hpp> <iostream>
int main(){
sf::RenderWindow window(sf::VideoMode(1000, 700), "project");
window.setFramerateLimit(60);
sf::RectangleShape rect;
int w = 100;
int h = 100;
rect.setSize(sf::Vector2f(w, h));
sf::Vector2f rectangle_position(500 - (w/2), 300 - (h/2));
rect.setPosition(rectangle_position);
float x_velocity = 3;
float y_velocity = 3;
while (window.isOpen()) {
sf::Event event;
while (window.pollEvent(event)) {
if (event.type == sf::Event::Closed) window.close();
if (sf::Keyboard::isKeyPressed(sf::Keyboard::Escape)) window.close();
}
if (rectangle_position.x > 1000 - w) {
x_velocity = x_velocity * -1;
}
if (rectangle_position.x < 1 ) {
x_velocity = x_velocity * -1;
}
if (rectangle_position.y > 700 - h) {
y_velocity = y_velocity * -1;
}
if (rectangle_position.y < 50) {
y_velocity = y_velocity * -1;
}
y_velocity = y_velocity + 3;
rectangle_position.x = rectangle_position.x + x_velocity;
rectangle_position.y = rectangle_position.y + y_velocity;
rect.setPosition(rectangle_position);
window.clear();
window.draw(rect);
window.display();
}
}
In your implementation, once the bottom of the rectangle goes below the ground, you just reverse the velocity but never update the position of the rectangle. This causes the rectangle to sink below the ground.
You should make sure that the bottom of the rectangle never goes below the ground. This can be done by adding the following condition:
if (rectangle_position.y > 700 - h) {
// make sure that rectangle never goes below the ground
rectangle_position.y -= 3;
y_velocity = y_velocity * -1;
}
And the result is:
Hope it helps.

Double clicking in SFML doesnt work as expected

I am working on a recreation of minesweeper using cpp and SFML. I have coded the board and the tiles switch to their revealed states when you left click on them, however, I am running into a strange issue with the right click.
Since I want to be able to flag and unflag tiles, I created a texture called tile_foreground that stores a texture the same size as the tiles but is completely transparent. The idea is that the first click will flag the tile and draw the flag sprite and a 2nd click would unflag the tile and change the sprite texture to the empty png so that only the base of the tile shows, with the cycle continuing on further clicks.
When you right click, the first click wont register and it will take at least a 2nd click to place down a flag on the tile. Sometimes it takes more than 2 clicks and clicking on a tile, moving your mouse to a different tile and then back to the same tile without clicking on a different tile will not flag the tile. It seems that the program doesnt register the first click as a click and waits for another one from the same tile to register it.
I suspect this comes from the way I handle the clicking events since before I added the statement below, holding down the right button would make the sprites alternate quickly and infinitely.
event.type == sf::Event::MouseButtonReleased
Any input would be appreciated since I dont really know how I would fix this.
Below is my main.cpp file
#include <SFML/Graphics.hpp>
#include <random>
#include <iostream>
#include <fstream>
#include <string>
#include "Board.h"
#include "TextureManager.h"
void testFunc() {
sf::RenderWindow window(sf::VideoMode(200, 200), "SFML works!");
sf::CircleShape shape(100.f);
shape.setFillColor(sf::Color::Green);
while (window.isOpen())
{
sf::Event event;
while (window.pollEvent(event))
{
if (event.type == sf::Event::Closed)
window.close();
}
window.clear();
window.draw(shape);
window.display();
}
}
void loadMSImages() {
string files[21] = {"debug", "digits", "face_happy", "face_lose", "face_win", "flag", "mine",
"number_1", "number_2", "number_3" , "number_4" , "number_5" , "number_6",
"number_7" , "number_8", "test_1", "test_2", "test_3", "tile_hidden", "tile_revealed", "tile_foreground"};
for (int i = 0; i < 21; i += 1) {
TextureManager::LoadTexture(files[i]);
}
}
int main()
{
loadMSImages();
//testFunc(); // Test function to see if program is still working properly
// Reads config file to determine window size
int colNum;
int rowNum;
int mineNum;
std::fstream reader("boards\\config.cfg");
string readString;
if (!reader.is_open())
{
std::cout << "File could not be opened" << std::endl;
return 0;
}
// Reads col #, row #, and mine # in that order
std::getline(reader, readString);
colNum = stoi(readString);
std::getline(reader, readString);
rowNum = stoi(readString);
std::getline(reader, readString);
mineNum = stoi(readString);
reader.close();
// Provided test boards have a size of 25 x 16
sf::RenderWindow window;
window.create(sf::VideoMode((colNum * 32), (rowNum * 32) + 100), "Minesweeper"); // Width, Height
window.setKeyRepeatEnabled(true);
window.setVerticalSyncEnabled(true);
Board testBoard(rowNum, colNum, mineNum);
testBoard.printBoard();
// Tile Testing Code
// Creating sprites for buttons on bottom of game
sf::Sprite testBoardOne;
sf::Sprite testBoardTwo;
sf::Sprite testBoardThree;
sf::Sprite debugButton;
sf::Sprite statusFace;
sf::Sprite timerDigitOne;
sf::Sprite timerDigitTwo;
sf::Sprite timerDigitThree;
// Setting the positions of these sprites
testBoardOne.setPosition(sf::Vector2f(((32 * colNum) - 64), ((32 * rowNum))));
testBoardTwo.setPosition(sf::Vector2f(((32 * colNum) -128), ((32 * rowNum))));
testBoardThree.setPosition(sf::Vector2f(((32 * colNum) - 192), ((32 * rowNum))));
debugButton.setPosition(sf::Vector2f(((32 * colNum) - 256), ((32 * rowNum))));
statusFace.setPosition(sf::Vector2f((((32 * colNum)/2)-32), ((32 * rowNum))));
// Loading the textures onto the sprites
testBoardOne.setTexture(TextureManager::GetTexture("test_1"));
testBoardTwo.setTexture(TextureManager::GetTexture("test_2"));
testBoardThree.setTexture(TextureManager::GetTexture("test_3"));
debugButton.setTexture(TextureManager::GetTexture("debug"));
statusFace.setTexture(TextureManager::GetTexture("face_happy"));
// 2D vector of tiles
std::vector<std::vector<Tile*>> tiles;
//Holding variables for creating Tile objects
Tile* holdingTile;
sf::Sprite* holdingSprite;
for (int i = 0; i < 25; i += 1)
{
std::vector<Tile*> holdingVec;
tiles.push_back(holdingVec);
for (int j = 0; j < 16; j += 1)
{
holdingTile = new Tile(0, i, j);
holdingSprite = new sf::Sprite();
holdingSprite->setTexture(TextureManager::GetTexture("tile_hidden"));
holdingSprite->setPosition(sf::Vector2f((32 * i), (32 * j)));
holdingTile->setBackgroundSprite(holdingSprite);
holdingSprite = new sf::Sprite();
//holdingSprite->setTexture(TextureManager::GetTexture("tile_foreground"));
holdingSprite->setPosition(sf::Vector2f((32 * i), (32 * j)));
holdingTile->setForegroundSprite(holdingSprite);
tiles.at(i).push_back(holdingTile);
}
}
//============================ GAME LOOP ======================================
// run the program as long as the window is open
while (window.isOpen())
{
// check all the window's events that were triggered since the last iteration of the loop
sf::Event event;
while (window.pollEvent(event))
{
// "close requested" event: we close the window
if (event.type == sf::Event::Closed)
window.close();
}
// Clears previous frame, draws new frame, and displays it
window.clear();
// Draws tiles on board
for (unsigned int i = 0; i < tiles.size(); i += 1)
{
for (unsigned int j = 0; j < tiles.at(i).size(); j += 1)
{
window.draw(*(tiles.at(i).at(j)->getBackgroundSprite()));
window.draw(*(tiles.at(i).at(j)->getForegroundSprite()));
}
}
//Draws "Constant" Buttons, such as debug mode and boards
window.draw(testBoardOne);
window.draw(testBoardTwo);
window.draw(testBoardThree);
window.draw(debugButton);
window.draw(statusFace);
window.display();
// Clicking handlers
if (sf::Mouse::isButtonPressed(sf::Mouse::Left))
{
// transform the mouse position from window coordinates to world coordinates
sf::Vector2f mouse = window.mapPixelToCoords(sf::Mouse::getPosition(window));
// retrieve the bounding box of the sprite
sf::FloatRect bounds;
for (unsigned int i = 0; i < tiles.size(); i += 1)
{
for (unsigned int j = 0; j < tiles.at(i).size(); j += 1)
{
bounds = tiles.at(i).at(j)->getBackgroundSprite()->getGlobalBounds();
if (bounds.contains(mouse))
{
//std::cout << "Sprite pressed" << std::endl;
tiles.at(i).at(j)->getBackgroundSprite()->setTexture(TextureManager::GetTexture("tile_revealed"));
}
}
}
}
//if (sf::Mouse::isButtonPressed(sf::Mouse::Right)) // WIP - Rapid oscillation of textures
if (sf::Mouse::isButtonPressed(sf::Mouse::Right) && event.type == sf::Event::MouseButtonReleased)
{
// transform the mouse position from window coordinates to world coordinates
sf::Vector2f mouse = window.mapPixelToCoords(sf::Mouse::getPosition(window));
// retrieve the bounding box of the sprite
sf::FloatRect bounds;
for (unsigned int i = 0; i < tiles.size(); i += 1)
{
for (unsigned int j = 0; j < tiles.at(i).size(); j += 1)
{
bounds = tiles.at(i).at(j)->getBackgroundSprite()->getGlobalBounds();
if (bounds.contains(mouse))
{
std::cout << "Tile right clicked" << std::endl;
if (tiles.at(i).at(j)->isFlagged)
{
tiles.at(i).at(j)->unflagTile();
tiles.at(i).at(j)->getForegroundSprite()->setTexture(TextureManager::GetTexture("tile_foreground"));
}
else
{
tiles.at(i).at(j)->flagTile();
tiles.at(i).at(j)->getForegroundSprite()->setTexture(TextureManager::GetTexture("flag"));
}
}
}
}
}
}
// Make sure to clear the textures at the end of the program to avoid errors
TextureManager::Clear();
return 0;
}
The problem is that you use the sf::Event event variable outside the while (window.pollEvent(event)) loop, so when you use the event, the last event type is assigned to it, which does not necessarily have to be MouseButtonReleased but can be one of these:
https://www.sfml-dev.org/documentation/2.5.1/classsf_1_1Event.php#af41fa9ed45c02449030699f671331d4a
Solution:
Move this condition:
if (sf::Mouse::isButtonPressed(sf::Mouse::Right) && event.type == sf::Event::MouseButtonReleased)
to the while (window.pollEvent(event)) loop and change it to:
if (event.type == sf::Event::MouseButtonReleased && event.mouseButton.button == sf::Mouse::Right)

Cannot get smooth movement in SFML

I searched on this topic and found that using sf::Clock to implement frame independent update(using deltaTime) can help to solve it. However even after adding it the paddle movement stutters a bit. On the other hand when I shift the entire Playing case to the event polling loop without using deltatime the game seems to run smoothly.
How do I go about using sf::Clock properly in my code and why does my game seems to run smoothly when I shift the Playing case in event pool loop without even using deltatime?
Game initialization:
void Game::start() {
if (_gameState != Uninitialized) {
return;
}
//Creating window
_mainWindow.create(sf::VideoMode(SCREEN_WIDTH, SCREEN_HEIGHT, 32), "Pong");
_gameState = ShowingMenu;
//Adding game entities to the manager
VisibleGameObject *paddle1 = new PlayerPaddle("Player1", 1.0f, sf::Keyboard::Key::Up, sf::Keyboard::Key::Down);
VisibleGameObject *paddle2 = new PlayerPaddle("Player2", 1.0f, sf::Keyboard::Key::W, sf::Keyboard::Key::S);
VisibleGameObject *background = new Background("Background", 0.0f);
paddle1 -> setPosition(SCREEN_WIDTH - (paddle1 -> getWidth()), 0);
paddle2->setPosition(0, 0);
manager.addObject(paddle1);
manager.addObject(paddle2);
manager.addObject(background);
//Starting Clock
deltaTime = 0.0f;
frameClock.restart();
while (!isExiting()) {
gameLoop();
}
_mainWindow.close();
}
Game Loop :
void Game::gameLoop()
{
static bool firstPass = true;
sf::Event currentEvent;
//Event loop
while(_mainWindow.pollEvent(currentEvent) || firstPass)
{
if (firstPass) {
currentEvent = sf::Event();
currentEvent.type = sf::Event::GainedFocus;
firstPass = false;
}
if (currentEvent.type == sf::Event::Closed)
{
_gameState = Exiting;
}
switch (_gameState)
{
case ShowingMenu:
{
showingMenu();
break;
}
case Paused:
{
break;
}
default:
break;
}
}
//Extracting deltaTime to update game logic
deltaTime = frameClock.restart().asSeconds();
if(_gameState == Playing)
{
manager.updateAllLayers(deltaTime);
manager.drawAllLayers(_mainWindow);
_mainWindow.display();
}
}
Paddle Update Logic:
void PlayerPaddle::update(const float & elapsedTime)
{
sf::Vector2f currentPos = getPosition();
float displacement = 0.0f;
if (sf::Keyboard::isKeyPressed(controls.up))
{
displacement = -speed * elapsedTime;
}
else if (sf::Keyboard::isKeyPressed(controls.down))
{
displacement = speed * elapsedTime;
}
if (displacement + currentPos.y < 0.0f)
{
setPosition(currentPos.x, 0.0f);
return;
}
else if (displacement + currentPos.y + getHeight() > Game::SCREEN_HEIGHT)
{
setPosition(currentPos.x, Game::SCREEN_HEIGHT - getHeight());
return;
}
setPosition(currentPos.x, currentPos.y + displacement);
}
I don't have enough reputation to post a comment so I'll have to make this an answer...
You update (and draw) every frame. Your game loop doesn't make sense if you want to implement a fixed update time step.
This is how your game loop should look like. I use your variable names for your convenience:
// ...
sf::Clock frameClock;
const sf::Time timePerFrame = sf::seconds(1.0f / 60.0f);
sf::Time timeSinceLastUpdate = sf::Time::Zero;
while (_mainWindow.isOpen()) {
timeSinceLastUpdate += frameClock.restart();
// events
{
sf::Event evt;
while (_mainWindow.pollEvent(evt)) {
//...
}
}
// update
{
while (timeSinceLastUpdate > timePerFrame) {
timeSinceLastUpdate -= timePerFrame;
manager.updateAllLayers(timePerFrame);
}
}
// render
{
_mainWindow.clear();
// ...
_mainWindow.display();
}
}
// ...
This updates your game at a fixed rate (1/60s) and renders it whenever possible (you can use setFramerateLimit() to limit the FPS; this won't affect the fixed update interval, so no problem there).
You now pass sf::Time to your manager.updateAllLayers which is used like your elapsedTime (it has functions like .asSeconds() so essentially nothing changes but you'll obviously have to adjust the values for speed)

How do I slow down my sprite animations?

Currently I have this player.cpp class that I'm using for my sprite animations. I'm using a counter to update every frame. It animates, but it flies through the animations.
I want to slow this down. I found code that can be used to slow down sprite animations but I'm unsure how to implement it into my current program.
Below are my player.cpp file and following it is the code I found that can slow down sprite animations. When I've tried to add a clock to the counterWalking++ it didn't animate at all, and I've tried implementing this code to the same effect.
player::player()
{
rect.setSize(sf::Vector2f(32, 32));
rect.setFillColor(sf::Color::White);
rect.setPosition(300, 300);
sprite.setTextureRect(sf::IntRect(0, 0, 32, 32));
}
void player::update()
{
sprite.setPosition(rect.getPosition());
}
void player::updateMovement()
{
if (sf::Keyboard::isKeyPressed(sf::Keyboard::Right)) {
if (canMoveRight == true) {
rect.move(movementSpeed, 0);
sprite.setTextureRect(sf::IntRect(counterWalking * 32, 64, 32, 32));
direction = 4;
canMoveUp = true;
canMoveDown = true;
canMoveLeft = true;
canMoveRight = true;
}
}
else if (sf::Keyboard::isKeyPressed(sf::Keyboard::Left)) {
if (canMoveLeft == true) {
rect.move(-movementSpeed, 0);
sprite.setTextureRect(sf::IntRect(counterWalking * 32, 32, 32, 32));
direction = 3;
canMoveUp = true;
canMoveDown = true;
canMoveLeft = true;
canMoveRight = true;
}
}
else if (sf::Keyboard::isKeyPressed(sf::Keyboard::Up)) {
if (canMoveUp == true) {
rect.move(0, -movementSpeed);
sprite.setTextureRect(sf::IntRect(counterWalking * 32, 96, 32, 32));
direction = 1;
canMoveUp = true;
canMoveDown = true;
canMoveLeft = true;
canMoveRight = true;
}
}
else if (sf::Keyboard::isKeyPressed(sf::Keyboard::Down)) {
if (canMoveDown == true) {
rect.move(0, movementSpeed);
sprite.setTextureRect(sf::IntRect(counterWalking * 32, 0, 32, 32));
direction = 2;
canMoveUp = true;
canMoveDown = true;
canMoveLeft = true;
canMoveRight = true;
}
}
else {
//Player not moving
}
counterWalking++;
if (counterWalking == 3)
counterWalking = 0;
}
Here is the code I found that displays a slow animation:
int main()
{
sf::RenderWindow renderWindow(sf::VideoMode(640, 480), "Demo Game");
sf::Event event;
sf::Texture texture;
texture.loadFromFile("images/player.png");
sf::IntRect rectSourceSprite(0, 0, 32, 32);
sf::Sprite sprite(texture, rectSourceSprite);
sf::Clock clock;
while (renderWindow.isOpen()) {
while (renderWindow.pollEvent(event)) {
if (event.type == sf::Event::EventType::Closed)
renderWindow.close();
}
if (clock.getElapsedTime().asSeconds() > 1.0f) {
if (rectSourceSprite.left == 96)
rectSourceSprite.left = 0;
else
rectSourceSprite.left += 32;
sprite.setTextureRect(rectSourceSprite);
clock.restart();
}
renderWindow.clear();
renderWindow.draw(sprite);
renderWindow.display();
}
}
Since a solution has been given in comment but not implemented in an answer, here's some kind of "code review"
Key Binding
This code is actually using the sf::Keyboard::isKeyPressed and sf::Keyboard::isKeyReleased wich needs to be called every loop while a simple boolean switched when the key is pressed/released could to the work using events.
while (renderWindow.pollEvent(event)) {
if (event.type == sf::Event::EventType::Closed)
renderWindow.close();
}
The Event used in the main loop does also contain information about KeyEvents but isn't used that way. I'll suggest sending the evet to the player eac time a key Event happens:
while (renderWindow.pollEvent(event)) {
switch(event.type){
case sf::Event::EventType::Closed:
renderWindow.close();
break;
case sf::Event::KeyPressed: case sf::Event::KeyReleased:
myPlayer.keyEvent(event);
break;
}
}
The keyEvent function in player should then look like this:
void player::keyEvent(sf::Event event){
//Keycode of your keyboard's arrows goes from 71 to 74
if (event.key.code >= 71 && event.key.code <= 74){
//Gets the array ID from the enumeration value
int ID = event.key.code - 71;
//Stores false if the key is release, and true if it's pressed
keys[ID] = (event.type == sf::Event::KeyPressed);
}
}
Wich changes each values of the array in Player.h:
private:
bool keys[4];
Movement
Now all you have to do is call the player update() function in your game loop each second:
if (clock.getElapsedTime().asSeconds() > 1.0f) {
if (rectSourceSprite.left == 96)
rectSourceSprite.left = 0;
else
rectSourceSprite.left += 32;
sprite.setTextureRect(rectSourceSprite);
myPlayer.update();
clock.restart();
}
In the update() function, ou will then build you movement vector based on wich key is pressed:
void player::update()
{
sf::Vector2f movementVector(0,0);
//Left
if (keys[0]){
movementVector.x -= movementSpeed;
//Sends the sprite Rectangle position based on the movement type
move(32);
}
//Right
if (keys[1]){
movementVector.x += movementSpeed;
move(64);
}
//Up
if (keys[2]){
movementVector.y -= movementSpeed;
move(96);
}
//Down
if (keys[3]){
movementVector.y += movementSpeed;
move(0);
}
}
The move function will then move your sprite Position depending on the movement vector and the counter, the sprite will then be set.
Your movement counter will be incremented up to 30 and your player may only move when this counter is equal to 0, 10 or 20:
void move(int spritePos){
//Here, the check() function should tell if the player isn't going outside of the screen / in a wall
if (check(sprite.getPosition() + movementVector)){
sprite.move(movementVector);
++counterWalking %= 30;
if(!counterWalking % 10)
sprite.setTextureRect(sf::IntRect(counterWalking / 10 * 32, spritePos, 32, 32));
}
}
There are multiple ways of doing this, that's only the way I would do it
Sounds like you might need to learn about controlling the time-step. Essentially you only execute certain code when a desired amount of time has passed.
You'll commonly see this site referenced so maybe check it out:
https://gafferongames.com/post/fix_your_timestep/

How can I set gravity using this code?

I am trying to make a game and am stuck on gravity..... In the following code a rectangle stands for a player and when I press up key it moves in y-axis but when I activate gravity on it (i.e resetting its previous position) it does not animate (i.e. It does not jumps) instead it just stays in its position. I am using SFML library of C++ and that's a game development tool. Please Help!
#include <SFML/Graphics.hpp>
int main(){
sf::RenderWindow window(sf::VideoMode(800, 600, 32), "Gravity");
sf::RectangleShape rectangle;
rectangle.setSize(sf::Vector2f(100, 100));
rectangle.setFillColor(sf::Color::Black);
rectangle.setPosition(sf::Vector2f(10, 350));
while(window.isOpen())
{
sf::Event Event;
while(window.pollEvent(Event))
{
if(Event.type == sf::Event::Closed)
{
window.close();
}
}
if(sf::Keyboard::isKeyPressed(sf::Keyboard::Up))
{
rectangle.move(0, -1);
}
if(rectangle.getPosition().y >= 350-1)
{
rectangle.setPosition(0, 350);
}
window.display();
window.clear(sf::Color::Cyan);
window.draw(rectangle);
}
}
Theoretically your code would work, but there's one significant problem:
Your initial position is 350.
Now your "jumping code" (which will allow the player to fly indefinitely!) triggers and your position is changed to 349.
However, your code keeping the player from dropping off the screen (y >= 350-1) essentially resolves to the check y >= 349, which will be true, so your position is permanently reset to 350.
To solve this, just remove the -1 or replace the >= operator with >.
While your approach should be working (once the fix above is applied), you should rethink your strategy and store a velocity in addition to a position. I've recently written the following example code. It's far from being perfect, but it should teach you a few basics for a jump and run game (not necessarily the only way to do such things):
Allow the player to jump.
Apply gravity.
Allow the player to determine jump height based on how long he holds down a key.
#include <SFML/Graphics.hpp>
int main(int argc, char **argv) {
sf::RenderWindow window;
sf::Event event;
sf::RectangleShape box(sf::Vector2f(32, 32));
box.setFillColor(sf::Color::White);
box.setOrigin(16, 32);
box.setPosition(320, 240);
window.create(sf::VideoMode(640, 480), "Jumping Box [cursor keys + space]");
window.setFramerateLimit(60);
window.setVerticalSyncEnabled(false);
// player position
sf::Vector2f pos(320, 240);
// player velocity (per frame)
sf::Vector2f vel(0, 0);
// gravity (per frame)
sf::Vector2f gravity(0, .5f);
// max fall velocity
const float maxfall = 5;
// run acceleration
const float runacc = .25f;
// max run velocity
const float maxrun = 2.5f;
// jump acceleration
const float jumpacc = -1;
// number of frames to accelerate in
const unsigned char jumpframes = 10;
// counts the number of frames where you can still accelerate
unsigned char jumpcounter = 0;
// inputs
bool left = false;
bool right = false;
bool jump = false;
while (window.isOpen()) {
while (window.pollEvent(event)) {
switch(event.type) {
case sf::Event::KeyPressed:
case sf::Event::KeyReleased:
switch (event.key.code) {
case sf::Keyboard::Escape:
window.close();
break;
case sf::Keyboard::Left:
left = event.type == sf::Event::KeyPressed;
break;
case sf::Keyboard::Right:
right = event.type == sf::Event::KeyPressed;
break;
case sf::Keyboard::Space:
jump = event.type == sf::Event::KeyPressed;
break;
}
break;
case sf::Event::Closed:
window.close();
break;
}
}
// logic update start
// first, apply velocities
pos += vel;
// determine whether the player is on the ground
const bool onground = pos.y >= 480;
// now update the velocity by...
// ...updating gravity
vel += gravity;
// ...capping gravity
if (vel.y > maxfall)
vel.y = maxfall;
if (left) { // running to the left
vel.x -= runacc;
}
else if (right) { // running to the right
vel.x += runacc;
}
else { // not running anymore; slowing down each frame
vel.x *= 0.9;
}
// jumping
if (jump) {
if (onground) { // on the ground
vel.y += jumpacc * 2;
jumpcounter = jumpframes;
}
else if (jumpcounter > 0) { // first few frames in the air
vel.y += jumpacc;
jumpcounter--;
}
}
else { // jump key released, stop acceleration
jumpcounter = 0;
}
// check for collision with the ground
if (pos.y > 480) {
vel.y = 0;
pos.y = 480;
}
// check for collision with the left border
if (pos.x < 16) {
vel.x = 0;
pos.x = 16;
}
else if (pos.x > 624) {
vel.x = 0;
pos.x = 624;
}
// logic update end
// update the position
box.setPosition(pos);
window.clear();
window.draw(box);
window.display();
}
return 0;
}