File indexing completed on 2022-09-27 12:31:12

0001 /*
0002     SPDX-FileCopyrightText: 2003-2008 Cies Breijs <cies AT kde DOT nl>
0003 
0004     SPDX-License-Identifier: GPL-2.0-or-later
0005 */
0006 
0007 #include "sprite.h"
0008 
0009 #include <math.h>
0010 
0011 #include <QSvgRenderer>
0012 
0013 
0014 const int SPRITE_SIZE = 30;
0015 
0016 Sprite::Sprite()
0017     : QGraphicsSvgItem(QStringLiteral(":turtle.svg"))
0018 {
0019     m_angle = 0;
0020     m_speed = 0;
0021 
0022     setAngle(0);
0023 }
0024 
0025 void Sprite::setSpriteSize(int size)
0026 {
0027     int w = renderer()->defaultSize().width();
0028     int h = renderer()->defaultSize().height();
0029     
0030     if (size <= 0 || w <= 0 || h <= 0) return;
0031     
0032     qreal s = (static_cast<qreal>(size)) / ((w > h) ? w : h);
0033     
0034     setTransform(QTransform::fromScale(s, s), true);
0035 }
0036 
0037 void Sprite::setAngle(double degrees)
0038 {
0039     resetTransform();
0040     setSpriteSize(SPRITE_SIZE);
0041     
0042     // Default rotation is done with the top-left corner of the SVG as the rotation point,
0043     // but we want to the rotation to be around the SVG's center...
0044     // This is why this "translation" is needed before the actual rotation.
0045     QTransform transform = QTransform::fromTranslate(
0046         renderer()->defaultSize().width()  * cos((degrees-135) * M_PI/180) * sqrt(static_cast<double>(2.0))/2,
0047         renderer()->defaultSize().height() * sin((degrees-135) * M_PI/180) * sqrt(static_cast<double>(2.0))/2
0048     );
0049     transform.rotate(degrees);
0050     setTransform(transform, true);
0051     m_angle = degrees;
0052 
0053     //TODO: Check if the update can be done more efficiently
0054     update();
0055 }