gpt4 book ai didi

c++ - 如何使用 C++ 在 SFML 中播放播放器

转载 作者:太空狗 更新时间:2023-10-29 20:10:56 25 4
gpt4 key购买 nike

我正在使用 SFML 使用 C++ 编写游戏。我已经编写了一个移动播放器的代码,但是当游戏开始播放器时,播放器会移动,但是当我离开按钮时播放器会返回到原来的位置。你能帮帮我吗?

主要内容:

#include <iostream>
#include <SFML/Graphics.hpp>

int main() {

sf::RenderWindow window(sf::VideoMode(1320, 840), "Window");
window.setPosition(sf::Vector2i(150, 50));
window.setSize(sf::Vector2u(1320, 840));
window.getPosition();
window.setVerticalSyncEnabled(true);
window.setFramerateLimit(5);
window.getSize();

while (window.isOpen()) {

window.clear(sf::Color::White);

//texture
sf::Texture texture;
if (!texture.loadFromFile("/users/gaetanodonnarumma/desktop/background1.png", sf::IntRect(0, 0, 1320, 840))) {
return -1;
}

sf::Texture playerTexture;
if (!playerTexture.loadFromFile("/users/gaetanodonnarumma/desktop/quadrato-giallo.jpg", sf::IntRect(0, 0, 70, 70))) {
return -1;
}

//sprite
sf::Sprite backgroud;
backgroud.setTexture(texture);

sf::Sprite player;
double pX = 0;
double pY = 770;
player.setTexture(playerTexture);
player.setPosition(sf::Vector2f(pX, pY));
player.getPosition();

sf::Event event;

while (window.pollEvent(event)) {

if (event.type == sf::Event::Closed) {
window.close();
}

if (event.type == sf::Event::KeyPressed) {
if (event.key.code == sf::Keyboard::D) {
player.move(10.f, 0.f);
}
}

if (event.type == sf::Event::KeyPressed) {
if (event.key.code == sf::Keyboard::D) {
player.setPosition(pX + 10, 770);
}

}

if (event.type == sf::Event::KeyPressed) {
if (event.key.code == sf::Keyboard::A) {
player.move(-5.f, 0.f);
}
}
}

//draw
window.draw(backgroud);
window.draw(player);

window.display();

}

return 0;

}

最佳答案

您所有的初始化代码都在每一帧上运行。这意味着在每一帧上,您都在创建(和销毁)一个新玩家,设置其纹理并将其位置设置为 [0, 770]

将所有初始化移动到主绘制循环开始之前(while (window.isOpen()) 之前)。

关于c++ - 如何使用 C++ 在 SFML 中播放播放器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35772056/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com