1
int main() {
sf::RenderWindow window;
sf::Vector2i centerWindow((sf::VideoMode::getDesktopMode().width/2) - 445, (sf::VideoMode::getDesktopMode().height/2) - 480);
window.create(sf::VideoMode(900, 900), "SFML Game", sf::Style::Titlebar | sf::Style::Close);
window.setPosition(centerWindow);
window.setKeyRepeatEnabled(true);
sf::Texture wallTxture;
sf::Sprite wall;
if (!wallTxture.loadFromFile("wall.png")) {
std::cerr << "Error\n";
}
wall.setTexture(wallTxture);
//Gravity Vars:
int groundHeight = 750;
bool isJumping = false;
//Movement Vars:
bool goingRight = false;
bool goingLeft = false;
//Set View Mode:
sf::View followPlayer;
followPlayer.reset(sf::FloatRect(0, 0, window.getSize().x, window.getSize().y));
Player player("newPlayer.png");
player.setPos({ 800, 800 });
sf::Vector2f position(window.getSize().x/2, window.getSize().y/2);
//Main Loop:
while (window.isOpen()) {
const float moveSpeed = 0.1;
sf::Event Event;
if (sf::Keyboard::isKeyPressed(sf::Keyboard::Up)) {
isJumping = true;
//Handle Movement While Jumping:
if (goingLeft == true) {
player.move({ -moveSpeed, -moveSpeed });
}
else if (goingRight == true) {
player.move({ moveSpeed, -moveSpeed });
}
else {
player.move({ 0, -moveSpeed });
}
}
else if (sf::Keyboard::isKeyPressed(sf::Keyboard::Down)) {
player.move({ 0, moveSpeed });
}
else if (sf::Keyboard::isKeyPressed(sf::Keyboard::Left)) {
player.move({ -moveSpeed, 0 });
goingLeft = true;
player.flipX('l');
}
else if (sf::Keyboard::isKeyPressed(sf::Keyboard::Right)) {
player.move({ moveSpeed, 0 });
goingRight = true;
player.flipX('r');
}
//Event Loop:
while (window.pollEvent(Event)) {
switch (Event.type) {
case sf::Event::Closed:
window.close();
case sf::Event::KeyReleased:
if (Event.key.code == sf::Keyboard::Up) {
isJumping = false;
}
else if (Event.key.code == sf::Keyboard::Left) {
goingLeft = false;
}
else if (Event.key.code == sf::Keyboard::Right) {
goingRight = false;
}
}
}
if (player.getX() > window.getSize().x) {
position.x = player.getX();
}
else {
position.x = window.getSize().x;
}
//If player is in air and not jumping:
if (player.getY() < groundHeight && isJumping == false) {
player.move({ 0, moveSpeed });
}
followPlayer.setCenter(position);
window.clear();
window.setView(followPlayer);
window.draw(wall);
player.drawTo(window);
window.display();
}
}
這是我的代碼。我想要做的是創建一個2D平臺的sidescroller。一切正常,除非精靈經過某個點時它會消失。當我在同一時間跳躍並在空中移動時也會發生這種情況。我不明白爲什麼會發生這種情況,任何幫助將不勝感激:)SFML/C++雪碧在某些點後消失
它始終是有用的:1.適當地格式化SO代碼(您可以使用代碼按鈕將所有代碼4空格右移)。 2.解釋代碼在做什麼。 3.由於你的問題是精靈,截圖將是非常有用的。 – grochmal
我的代碼是創建一個播放器,然後相機在他移動時跟隨播放器,然後在某個點後播放器因某種原因消失。我在這裏做了一個簡短的介紹:https://www.youtube.com/watch?v=YrDB7uwItIY&feature=youtu.be –
我發現這個問題,很好。出於某種原因,當我將我爲我的播放器類創建的flipX函數加入時,會發生此錯誤。所以現在我有一個新問題。爲什麼這個功能會導致這個問題: –