add svg sprite source
[blok] / boxitem.cpp
1 #include "boxitem.h"
2 #include <QDebug>
3 #include <cmath>
4 #include <QPainter>
5
6 #define MAEMO_WIDTH 800
7 #define MAEMO_HEIGHT 480
8
9 #define BOX2D_WIDTH 10
10 #define BOX2D_HEIGHT 6
11
12
13 BoxItem::BoxItem(QRectF rect, bool isStatic)
14     :QGraphicsPolygonItem()
15 {
16     setPolygon(QPolygonF(rect));
17     mIsStatic = isStatic;
18
19     m_body = 0;
20     mNeedRemoveFromWorld = false;
21
22
23 }
24
25 BoxItem::BoxItem(QPolygonF poly, bool isStatic )
26     :QGraphicsPolygonItem()
27 {
28     setPolygon(poly);
29     mIsStatic = isStatic;
30 }
31
32
33 void BoxItem::setup(b2World *world)
34 {
35     if ( polygon().size() > 8)
36     {
37         qDebug()<<"Error! Cannot build a physics polygon with more 8 vertex...";
38         return;
39     }
40
41     double angleRad = rotation() * M_PI / 180;
42
43
44     //#define MAEMO_WIDTH 800
45     //#define MAEMO_HEIGHT 480
46
47     //#define BOX2D_WIDTH 10
48     //#define BOX2D_HEIGHT 6
49
50
51
52     m_bodyDef.userData = this;
53     m_bodyDef.position.Set(pos().x() * 10/800, pos().y() * 6/480);
54     m_bodyDef.angle =  angleRad;
55
56     m_polygonDef.friction = 0.3f;
57     m_polygonDef.density  =    1.0f;
58     m_polygonDef.restitution  =    0.5f;
59     m_polygonDef.vertexCount = polygon().count() - 1;
60     //---CONSTRUCT A POYLGON SHAPE
61     int i=0;
62     QPolygonF poly  = polygon();
63     poly.remove(poly.count()-1);
64     foreach (QPointF p, poly)
65     {
66         m_polygonDef.vertices[i].Set(p.x()* 10/800,p.y()* 6/480);
67         ++i;
68     }
69
70     m_body = world->CreateBody(&m_bodyDef);
71     m_body->CreateShape(&m_polygonDef);
72     if (!mIsStatic)
73         m_body->SetMassFromShapes();
74
75
76 }
77 void BoxItem::updatePhysics()
78 {
79     resetTransform();
80
81
82     double factorX =BOX2D_WIDTH / MAEMO_WIDTH;
83     double factorY =BOX2D_HEIGHT / MAEMO_HEIGHT;
84
85     double angleDeg = m_body->GetAngle() * 180 / M_PI;
86     setPos(m_body->GetPosition().x*800/10, m_body->GetPosition().y*480/6);
87     setRotation(angleDeg);
88
89 }
90
91 void BoxItem::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget)
92 {
93
94     painter->setBrush(brush());
95     painter->setPen(pen());
96     painter->drawPolygon(polygon());
97
98
99 }
100
101 b2Body* BoxItem::body()
102 {
103 if ( m_body == 0)
104     return 0;
105
106 return m_body;
107
108 }