How to animate chracter ?
Unsolved
Game Development
-
Hello guys I have a game screen and have a chracter. I want make animate moving my chracter but how ? Can anyone share their experience with this?
-
@NullByte said in How to animate chracter ?:
I want make animate moving my chracter but how ?
By using Sprites: https://doc.qt.io/qt-5/qtquick-effects-sprites.html
Here's an example app: https://doc.qt.io/qt-5/qtdoc-demos-maroon-example.html
-
Sprite animation using QPainter:
You can download the "sprites-cat-running.png" sprite sheet here: https://plnkr.co/edit/zjYT0KTfj50MejT9?preview
main.cpp
#include <QtWidgets/QApplication> #include <QtWidgets/QWidget> #include <QtGui/QPainter> #include <QtGui/QImage> #include <QtCore/QTimer> #include <QtCore/QElapsedTimer> #include <QtCore/QDebug> #define N_FRAMES 8 class Window : public QWidget { Q_OBJECT public: Window() { setWindowTitle("Qt C++"); resize(512, 256); // Download a sprite sheet here: // https://plnkr.co/edit/zjYT0KTfj50MejT9?preview m_spriteSheet.load(":/Sprites/sprites-cat-running.png"); int index = 0; for (int i = 0; i < 2; i++ ) { for (int j = 0; j < 4; j++) { m_frames[index] = QPoint(j * m_sw, i * m_sh); qDebug() << m_frames[index]; index++; } } connect(&m_timer, &QTimer::timeout, this, &Window::animationLoop); m_timer.start(1000.f/60.f); m_elapsedTimer.start(); } private: QTimer m_timer; QElapsedTimer m_elapsedTimer; float m_deltaTime; float m_animationTime = 0.f; const float m_animationSpeed = 100.f; QImage m_spriteSheet; QPoint m_frames[N_FRAMES]; int m_frameIndex = 0; int m_x, m_y; const int m_sw = 512, m_sh = 256; // Source image width and height private slots: void animationLoop() { m_deltaTime = m_elapsedTimer.elapsed(); m_elapsedTimer.restart(); m_animationTime += m_deltaTime; if (m_animationTime > m_animationSpeed) { m_animationTime = 0; m_x = m_frames[m_frameIndex].x(); m_y = m_frames[m_frameIndex].y(); m_frameIndex++; if (m_frameIndex >= N_FRAMES) { m_frameIndex = 0; } } update(); } private: void paintEvent(QPaintEvent *event) { Q_UNUSED(event); QPainter qp(this); qp.drawImage(0, 0, m_spriteSheet, m_x, m_y, m_sw, m_sh); } }; #include "main.moc" int main(int argc, char *argv[]) { QApplication a(argc, argv); Window w; w.show(); return a.exec(); }