【发布时间】:2014-06-22 18:35:42
【问题描述】:
这是我的代码:
#include <SFML/Graphics.hpp>
#include <iostream>
#include <Windows.h>
int main()
{
sf::RenderWindow window(sf::VideoMode(800, 600), "SFML Game");
window.setFramerateLimit(200);
//Variable that keeps the game loop running
bool play = true;
//Event object holding all events
sf::Event event;
//States for button/events
bool Left = false;
bool Right = false;
bool space = false;
//Variables
int rectXPosition = 375; //Rectangles X position
int rectYPosition = 400; //Rectangles Y position
//Images
sf::Texture image1;
if (image1.loadFromFile("Images/GreekSoldier.png") == -1)
{
std::cout << "FAILED!!!" << "\n";
return 1;
}
//Render shapes
sf::RectangleShape rect;
rect.setSize(sf::Vector2f(77, 150)); //Width and height
rect.setPosition(375, 400); //Position
rect.setFillColor(sf::Color::White); //Color
rect.setTexture(&image1);
//Game loop
while (play == true)
{
//EVENTS
while (window.pollEvent(event))
{
if (event.type == sf::Event::KeyPressed && event.key.code == sf::Keyboard::Left)
{
//Set the state to true
Left = true;
}
if (event.type == sf::Event::KeyPressed && event.key.code == sf::Keyboard::Right)
{
Right = true;
}
if (event.type == sf::Event::KeyPressed && event.key.code == sf::Keyboard::Space)
{
space = true;
}
//Event type is window closed
if (event.type == sf::Event::Closed)
{
//Set play to false in order to stop the game loop
play = false;
}
}
//LOGIC
if (Left == true)
{
int x = 0;
for (x = 1; x < 2; x++)
{
rectXPosition-=5; //X position variable of the rectangle
rect.setPosition(rectXPosition, rectYPosition);
window.clear();
window.draw(rect);
window.display();
Sleep(5);
}
Left = false;
}
if (Right == true)
{
int x = 0;
for (x = 1; x < 2; x++)
{
rectXPosition+= 5; //X position variable of the rectangle
rect.setPosition(rectXPosition, rectYPosition);
window.clear();
window.draw(rect);
window.display();
Sleep(5);
}
Right = false;
}
if (space == true)
{
int x = 0;
for (x = 1; x < 15; x++)
{
rectYPosition-= 3; //X position variable of the rectangle
rect.setPosition(rectXPosition, rectYPosition);
window.clear();
window.draw(rect);
window.display();
Sleep(10);
}
for (x = 1; x < 15; x++)
{
rectYPosition+= 3; //X position variable of the rectangle
rect.setPosition(rectXPosition, rectYPosition);
window.clear();
window.draw(rect);
window.display();
Sleep(10);
}
space = false;
}
//RENDERING
window.clear();
//Draw the rectangle shape
window.draw(rect);
window.display();
}
//Clean up and close the window
window.close();
return 0;
}
如何让运动更流畅?我怎样才能使矩形(士兵)可以同时跳跃和移动?以及如何停止它,当按住左键时,它实际上不需要 3 秒就可以移动?
如果你们懒得编译,只想看看我在说什么,我已经添加了一个 youtube 视频。 https://www.youtube.com/watch?v=g_JLwGh1Wgo
【问题讨论】:
-
对您来说最重要的提示是不要使用
KeyPressed事件进行连续操作。 -
什么是更好的解决方案?
-
看看样本是如何完成的,尤其是。 the pong example。你可以在我推荐的SFML Game Development 中找到更多有趣的东西。