Hi, I am makeing a pong game, and for my movement, the paddle stutters when it moves, like when you hold down a letter on the keyboard. Taking that in mind I compensated for it in my code. The same strategy worked in another program but not in this one.
main(pong)
pong.cpp:
#include <SFML/Graphics.hpp>
#include <SFML/Audio.hpp>
#include "paddle.hpp"
/* Program Flow
init -> mainMenu -> game -> exit / main
*/
int main(){
paddle cayle;
sf::RenderWindow window(sf::VideoMode(800,600), "Pong -By Cayle");
cayle.createSprite();
window.setVerticalSyncEnabled(true);
while(window.isOpen()){
sf::Event event;
while(window.pollEvent(event)){
if(event.type == sf::Event::Closed){window.close();}
cayle.processEvent(event);
}
window.clear(sf::Color::Black);
window.draw(cayle.sprite);
window.display();
}
return 0;
}
paddle class:
#include <string>
#include <SFML/Graphics.hpp>
#include "paddle.hpp"
int paddle::getInt(std::string var){
int data;
if(var == "xPos"){
data = this -> xPos;
}else if(var == "yPos"){
data = this -> yPos;
}else if(var == "length"){
data = this -> length;
}
return data;
}
int paddle::move(int distance){
this -> yPos += distance;
return this -> yPos;
}
void paddle::createSprite(){
this -> texture.loadFromFile("../resources/paddleTexture.png");
this -> sprite.setTexture(texture);
}
void paddle::processEvent(sf::Event event){
bool upPress, downPress, leftPress, rightPress;
if(event.type == sf::Event::KeyPressed){
if(event.key.code == sf::Keyboard::Left){
leftPress = true;
}
if(event.key.code == sf::Keyboard::Right){
rightPress = true;
}
if(event.key.code == sf::Keyboard::Up){
upPress = true;
}
if(event.key.code == sf::Keyboard::Down){
downPress = true;
}
}
if(event.type == sf::Event::KeyReleased){
if(event.key.code == sf::Keyboard::Left){
leftPress = false;
}
if(event.key.code == sf::Keyboard::Right){
rightPress = false;
}
if(event.key.code == sf::Keyboard::Up){
upPress = false;
}
if(event.key.code == sf::Keyboard::Down){
downPress = false;
}
}
if(upPress){this -> yPos -= this -> speed;}
if(downPress){this -> yPos += this -> speed;}
sprite.setPosition(this -> xPos, this -> yPos);
}
paddle class header:
#ifndef PADDLE_HPP
#define PADDLE_HPP
#include <string>
#include <SFML/Graphics.hpp>
class paddle{
private:
int speed;
int length;
public:
int xPos;
int yPos;
paddle(){
xPos = 60;
yPos = 300;
speed = 7;
length = 80;
}
sf::Texture texture;
sf::Sprite sprite;
void createSprite();
void processEvent(sf::Event);
int move(int distance);
int getInt(std::string var);
};
#endif