我正在尝试学习SFML和C ++,所以我决定尝试制作我自己的Ping Pong游戏但是由于某种原因,玩家1没有正确清理而且玩家2的速度慢得多且抖动(与玩家1相同)。 / p>
有人可以帮我解决这个问题吗?
#include <SFML/Graphics.hpp>
#include "ResourcePath.hpp"
#include <iostream>
class Paddel {
int speed = 3;
sf::Vector2f border;
sf::Vector2f size;
sf::Vector2f position;
sf::Vector2f screenSize;
public:
sf::RectangleShape shape;
Paddel(sf::Vector2f screenSize,int player)
{
this->screenSize = screenSize;
this->size = sf::Vector2f(20,100);
this->border = sf::Vector2f(8,6);
if(player == 1)
this->position = border;
else if(player == 2) {
position.x = (screenSize.x - size.x) - border.x;
position.y = border.y;
}
this->shape.setSize(this->size);
this->shape.setPosition(this->position);
}
void moveUp()
{
this->position.y -= this->speed;
if(this->position.y < this->border.y)
this->position.y += this->speed;
this->shape.setPosition(this->position);
}
void moveDown()
{
this->position.y += this->speed;
//100 - (600 + 5)
if(this->position.y > (this->screenSize.y - this->border.y) - this->size.y)
this->position.y -= this->speed;
this->shape.setPosition(this->position);
}
};
using std::cout;
using std::endl;
int main()
{
sf::Vector2f screenSize(800,600);
sf::RenderWindow Window(sf::VideoMode(screenSize.x,screenSize.y),"Ping Pong");
Window.setFramerateLimit(60);
Window.setVerticalSyncEnabled(true);
Paddel playerOne(screenSize,1);
Paddel playerTwo(screenSize,2);
const sf::Time TimePerFrame = sf::seconds(1.f/60.f);
sf::Clock clock;
sf::Time timeSinceLastUpdate = sf::Time::Zero;
sf::Time elapsedTime;
bool play = true;
while(Window.isOpen())
{
Window.clear();
sf::Event Event;
while(Window.pollEvent(Event))
{
if(Event.type == sf::Event::Closed)
Window.close();
}
elapsedTime = clock.restart();
timeSinceLastUpdate += elapsedTime;
if(play){
if(timeSinceLastUpdate > TimePerFrame){
if(sf::Keyboard::isKeyPressed(sf::Keyboard::W))
{
playerOne.moveUp();
}
if(sf::Keyboard::isKeyPressed(sf::Keyboard::S))
{
playerOne.moveDown();
}
if(sf::Keyboard::isKeyPressed(sf::Keyboard::Up))
{
playerTwo.moveUp();
}
if(sf::Keyboard::isKeyPressed(sf::Keyboard::Down))
{
playerTwo.moveDown();
}
if(sf::Keyboard::isKeyPressed(sf::Keyboard::P))
play = false;
}
Window.draw(playerOne.shape);
Window.draw(playerTwo.shape);
Window.display();
}
}
}
此外,如果我的代码混乱,那是因为我试图通过对C ++和SFML的了解很少来实现它。
答案 0 :(得分:0)
问题是Window.pollEvent(Event)
循环内发生了所有动作。为了解决这个问题,我把它从那里拿出来了。不知道它在那里做了什么。讨厌拼写错误!