first commit
[blok] / boxitem.cpp
diff --git a/boxitem.cpp b/boxitem.cpp
new file mode 100644 (file)
index 0000000..abe327d
--- /dev/null
@@ -0,0 +1,108 @@
+#include "boxitem.h"
+#include <QDebug>
+#include <cmath>
+#include <QPainter>
+
+#define MAEMO_WIDTH 800
+#define MAEMO_HEIGHT 480
+
+#define BOX2D_WIDTH 10
+#define BOX2D_HEIGHT 6
+
+
+BoxItem::BoxItem(QRectF rect, bool isStatic)
+    :QGraphicsPolygonItem()
+{
+    setPolygon(QPolygonF(rect));
+    mIsStatic = isStatic;
+
+    m_body = 0;
+    mNeedRemoveFromWorld = false;
+
+
+}
+
+BoxItem::BoxItem(QPolygonF poly, bool isStatic )
+    :QGraphicsPolygonItem()
+{
+    setPolygon(poly);
+    mIsStatic = isStatic;
+}
+
+
+void BoxItem::setup(b2World *world)
+{
+    if ( polygon().size() > 8)
+    {
+        qDebug()<<"Error! Cannot build a physics polygon with more 8 vertex...";
+        return;
+    }
+
+    double angleRad = rotation() * M_PI / 180;
+
+
+    //#define MAEMO_WIDTH 800
+    //#define MAEMO_HEIGHT 480
+
+    //#define BOX2D_WIDTH 10
+    //#define BOX2D_HEIGHT 6
+
+
+
+    m_bodyDef.userData = this;
+    m_bodyDef.position.Set(pos().x() * 10/800, pos().y() * 6/480);
+    m_bodyDef.angle =  angleRad;
+
+    m_polygonDef.friction = 0.3f;
+    m_polygonDef.density  =    1.0f;
+    m_polygonDef.restitution  =    0.5f;
+    m_polygonDef.vertexCount = polygon().count() - 1;
+    //---CONSTRUCT A POYLGON SHAPE
+    int i=0;
+    QPolygonF poly  = polygon();
+    poly.remove(poly.count()-1);
+    foreach (QPointF p, poly)
+    {
+        m_polygonDef.vertices[i].Set(p.x()* 10/800,p.y()* 6/480);
+        ++i;
+    }
+
+    m_body = world->CreateBody(&m_bodyDef);
+    m_body->CreateShape(&m_polygonDef);
+    if (!mIsStatic)
+        m_body->SetMassFromShapes();
+
+
+}
+void BoxItem::updatePhysics()
+{
+    resetTransform();
+
+
+    double factorX =BOX2D_WIDTH / MAEMO_WIDTH;
+    double factorY =BOX2D_HEIGHT / MAEMO_HEIGHT;
+
+    double angleDeg = m_body->GetAngle() * 180 / M_PI;
+    setPos(m_body->GetPosition().x*800/10, m_body->GetPosition().y*480/6);
+    setRotation(angleDeg);
+
+}
+
+void BoxItem::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget)
+{
+
+    painter->setBrush(brush());
+    painter->setPen(pen());
+    painter->drawPolygon(polygon());
+
+
+}
+
+b2Body* BoxItem::body()
+{
+if ( m_body == 0)
+    return 0;
+
+return m_body;
+
+}