I trying to make a platforming game in which I do basic input like going right,left,jump etc.
Main.cpp (only the while loop)
while (window.isOpen())
{
sf::Event event;
while (window.pollEvent(event)) {
if (event.type == sf::Event::Closed)
window.close();
}
if (sf::Keyboard::isKeyPressed(sf::Keyboard::Right)) {
player.MoveRight();
}
if (sf::Keyboard::isKeyPressed(sf::Keyboard::Left)) {
player.MoveLeft();
}
if (sf::Keyboard::isKeyPressed(sf::Keyboard::Space)) {
player.Jump();
}
player.MovePlayer();
window.clear();
window.draw(player.GetShape());
window.display();
}
Player.h
#pragma once
#include <SFML/Graphics.hpp>
class Player
{
private:
float speed = 5.0f;
float gravity = 3.0f;
float jumpSpeed = 2.0f;
sf::Vector2f velocity;
sf::Vector2f position;
public:
Player(); //Constructor
sf::RectangleShape playerShape;
sf::RectangleShape GetShape();
void MoveLeft();
void MoveRight();
void Jump();
void MovePlayer();
};
Player.cpp
#include <SFML/Graphics.hpp>
#include <iostream>
#include "Player.h"
Player::Player() {
playerShape.setFillColor(sf::Color::Green);
playerShape.setSize(sf::Vector2f(100.0f, 100.0f));
playerShape.setPosition(sf::Vector2f(10.0f, 350.0f));
}
sf::RectangleShape Player::GetShape() {
return playerShape;
}
void Player::MoveLeft() {
velocity.x = speed;
}
void Player::MoveRight() {
velocity.x = speed;
}
void Player::Jump() {
velocity.y = jumpSpeed;
}
void Player::MovePlayer() {
position.x += velocity.x;
position.y += velocity.y;
playerShape.move(position.x, position.y);
}
When I press suppose the right key but when I release it the sprite doesnt stop it goes on moving in that direction. How do I stop this.