我正在尝试在 sfml 中为精灵制作动画。目前,我可以移动精灵并在向不同方向移动时更改其图像,但我想在它移动时为其设置动画。我认为可能有一种方法可以使用 sf::Clock 来完成此操作,或者可能有更好的方法。所有精灵都在同一个精灵表上,因此我只需要找到一种方法,在沿某个方向移动时根据时间更改textureRect 的 X 和 Y 坐标。如果我遗漏了什么或者您有任何问题,我会尽我所能回答。
main.cpp
#include <iostream>
#include <SFML/Graphics.hpp>
#include "Character.hpp"
int main() {
sf::RenderWindow window(sf::VideoMode(5000, 5000), "Awesome Game" );
Character Boi("SpritesBoi.png", 0, 0, 5, 100);
sf::Sprite BoiSprite = Boi.getSprite();
Boi.SheetX = 0;
Boi.SheetY = 48;
while (window.isOpen()){
// check all the window's events that were triggered since the last iteration of the loop
sf::Event event;
while (window.pollEvent(event)){
// "close requested" event: we close the window
if (event.type == sf::Event::Closed){
window.close();
}
}
Boi.Move();
BoiSprite.setTextureRect(sf::IntRect(Boi.SheetX, Boi.SheetY, 110, 150));
BoiSprite.setPosition(Boi.x_pos, Boi.y_pos);
window.clear(sf::Color(255, 255, 255));
window.draw(BoiSprite);
window.display();
}
}
角色.hpp
#ifndef Character_hpp
#define Character_hpp
#include <stdio.h>
#include <SFML/Graphics.hpp>
#endif /* Character_hpp */
class Character{
public:
int health;
int speed;
int x_pos;
int y_pos;
int SheetX;
int SheetY;
sf::Texture texture;
sf::Sprite sprite;
Character(std::string image, int xlocation, int ylocation, int s, int h){
health = h;
speed = s;
x_pos = xlocation;
y_pos = ylocation;
texture.loadFromFile(image);
}
sf::Sprite getSprite() {
sprite.setTexture(texture);
sprite.setPosition(x_pos, y_pos);
sprite.setTextureRect(sf::IntRect(SheetX, SheetY, 110, 150));
return sprite;
}
void Move();
};
人物.cpp
#include "Character.hpp"
#include <iostream>
void Character::Move(){
//Up
if(sf::Keyboard::isKeyPressed(sf::Keyboard::Up)){
SheetX = 0;
SheetY = 192;
y_pos = y_pos - 1;
Up = true;
}
//Down
if(sf::Keyboard::isKeyPressed(sf::Keyboard::Down)){
SheetX = 0;
SheetY = 48;
y_pos = y_pos + 1;
Down = false;
}
//Left
if(sf::Keyboard::isKeyPressed(sf::Keyboard::Left)){
SheetX = 0;
SheetY = 480;
x_pos = x_pos - 1;
Left = true;
}
//Right
if(sf::Keyboard::isKeyPressed(sf::Keyboard::Right)){
SheetX = 0;
SheetY = 339;
x_pos = x_pos + 1;
Right = true;
}
//Up Right
if(sf::Keyboard::isKeyPressed(sf::Keyboard::Up) and sf::Keyboard::isKeyPressed(sf::Keyboard::Right)){
SheetX = 334;
SheetY = 490;
}
//Up Left
if(sf::Keyboard::isKeyPressed(sf::Keyboard::Up) and sf::Keyboard::isKeyPressed(sf::Keyboard::Left)){
SheetX = 333;
SheetY = 340;
}
//Down Right
if(sf::Keyboard::isKeyPressed(sf::Keyboard::Down) and sf::Keyboard::isKeyPressed(sf::Keyboard::Right)){
SheetX = 334;
SheetY = 48;
}
//Down Left
if(sf::Keyboard::isKeyPressed(sf::Keyboard::Down) and sf::Keyboard::isKeyPressed(sf::Keyboard::Left)){
SheetX = 334;
SheetY = 191;
}
}