void Package::update (uint32_t deltaTime) { CollectableEntity::update(deltaTime); if (_addRopeJointTo) { addRopeJoint(_addRopeJointTo); _addRopeJointTo = nullptr; } if ((_arrived || _delivered || isDestroyed()) && _ropeJoint) { removeRopeJoint(); } if (isCollected()) { setLinearDamping(0.0f); setAngularDamping(0.0); } if (!_target) { _target = _map.getPackageTarget(); // if we can't find a package target, we will destroy the package if (!_target) setDestroyed(); } if (!isCounted() && isDelivered()) { _map.countTransferedPackage(); setCounted(); } }
void Package::endContact (b2Contact* contact, IEntity* entity) { CollectableEntity::endContact(contact, entity); if (entity->isSolid() || entity->isPackage() || entity->isStone() || entity->isBorder()) { setLinearDamping(0.0f); setAngularDamping(0.0); } }
Bullet::Bullet(Circle circle, Item *p) : QBody(p) { setPosition(QPointF(circle.pos())); setLinearDamping(0); setBullet(true); setBodyType(Dynamic); auto fixture = std::make_unique<Box2DCircle>(this); fixture->setShadowCaster(false); fixture->setRadius(circle.radius()); fixture->setGroupIndex(-1); addFixture(std::move(fixture)); }
void Package::onContact (b2Contact* contact, IEntity* entity) { const bool oldCollectedState = isCollected(); CollectableEntity::onContact(contact, entity); if (!oldCollectedState && isCollected()) { _addRopeJointTo = entity; } else { if (entity->isSolid() || entity->isStone() || entity->isPackage()) { setLinearDamping(3.0f); setAngularDamping(1.0); if (isImpactVelocityMoreThan(contact, 1.5f)) _map.sendSound(getVisMask(), SoundTypes::SOUND_PACKAGE_COLLIDE, getPos()); } else if (entity->isBorder()) { const Border *b = assert_cast<const Border*, const IEntity*>(entity); if (!b->isTop()) { setLinearDamping(4.0f); setAngularDamping(1.0); } } else if (entity->isNpcAttacking()) { setDestroyed(true); } } }
Player * Player::create() { Size visibleSize = Director::getInstance()->getVisibleSize(); Point origin = Director::getInstance()->getVisibleOrigin(); Player * player = new Player(); if (player && player->initWithFile("GameScreen/player.png")) { player->autorelease(); player->initPlayer(); player->setPosition(Point(visibleSize.width / 2 + origin.x, visibleSize.height + origin.y)); auto player1Body = PhysicsBody::createBox(player->getContentSize(), PhysicsMaterial(0, 0, 0)); player1Body->setCollisionBitmask(0x000001); player1Body->setRotationEnable(false); //player1Body->setCategoryBitmask(0x02); player1Body->setContactTestBitmask(true); player1Body->setTag(10); player1Body->setDynamic(true); //player1Body->setVelocity(Vect(100, 247)); player1Body->setLinearDamping(0); //player1Body->applyForce(Vect(100, 245)); //Assign the body to sprite player->setPhysicsBody(player1Body); player->setPosition(Vec2(origin.x + visibleSize.width / 2, origin.y + visibleSize.height / 4)); player->setAnchorPoint(Point(0.5f, 0.5f)); player->setScale(.8); //player->pMovement(player); //this->addChild(sprite); return player; } CC_SAFE_DELETE(player); return NULL; }
cocos2d::PhysicsBody* RubeBody::createPhysicsBody() { if (0 == fixtures.size()) { return nullptr; } auto pb = cocos2d::PhysicsBody::create(); pb->setRotationEnable(this->getRotationEnable()); if (this->getBodyType() == 0) { //0 = static, 1 = kinematic, 2 = dynamic pb->setDynamic(false); } for (auto fixture: fixtures) { auto shape = fixture->getShape(this->scale); pb->addShape(shape); } pb->setLinearDamping(this->getLinearDamping()); pb->setAngularDamping(this->getAngularDamping()); //pb->setCollisionBitmask(1); //pb->setCategoryBitmask(1); return pb; }
void Game2::createtrap(double x, double y, double z, std::string name){ //create trap Trap *_trampa = Trap::create(); _trampa->setPosition3D(Vec3(x, y, z)); _trampa->setName(name); _trampas->addObject(_trampa); //create body auto _body = PhysicsBody::createEdgeBox(Size(35, 20), PhysicsMaterial(10, 0, 0.9f), 1.0, Vec2(-5, 10)); _body->setContactTestBitmask(true); _body->setDynamic(false); _body->setRotationEnable(false); _body->addMass(30.0); _body->addMoment(2.0); _body->setLinearDamping(0.8f); _trampa->setPhysicsBody(_body); addChild(_trampa); }
Player::Player(Item* parent) : QBody(parent), m_currentPathPoint(), m_going(false), m_punchSound(std::make_shared<QSound>(":/resources/punch_sound.wav")), m_object(this), m_score() { setBodyType(QBody::BodyType::Dynamic); auto circle = std::make_unique<Box2DCircle>(); circle->setRadius(2.5); circle->setFriction(0.0); circle->setDensity(1.0); circle->setPosition(QPointF(-2.5, -2.5)); circle->setCategories(QFixture::Category2); circle->setCollidesWith(QFixture::Category1); circle->setRestitution(0.2); addFixture(std::move(circle)); setPosition(QPointF(70, 950)); setLinearDamping(5); setAngularDamping(5); }
void Game2::createplatform(double x, double y, double z, double scale, double bodyscalex, double bodyscaley, double xoffset, double yoffset, std::string name){ //create platform Platform *_plataforma = Platform::create(); _plataforma->setScaleX(scale); _plataforma->setScaleY(10); _plataforma->setName(name); _plataforma->setPosition3D(Vec3(x, y, z)); _plataformas->addObject(_plataforma); //create body auto _body = PhysicsBody::createEdgeBox(Size(bodyscalex, bodyscaley), PhysicsMaterial(10, 0, 0.9f), 1.0, Vec2(xoffset, yoffset)); _body->setContactTestBitmask(true); _body->setDynamic(false); _body->setRotationEnable(false); _body->addMass(30.0); _body->addMoment(2.0); _body->setLinearDamping(0.8f); _plataforma->setPhysicsBody(_body); addChild(_plataforma); }
void HelloWorld::addPhysicsSprite() { // _scene->getPhysicsWorld()->setUpdateRate(5.0f); // wall 添加物理边境 Size size = VisibleRect::getVisibleRect().size; auto wall = Node::create(); //给节点添加静态矩形刚体(PhysicsBody)并带材质(PhysicsMaterial) wall->setPhysicsBody(PhysicsBody::createEdgeBox(Size(size.width - 5, size.height - 5), PhysicsMaterial(0.1f, 1.0f, 1.0f))); // wall->getPhysicsBody()->setDynamic(false);//设置为静态刚体(Edge // wall->getPhysicsBody()->setEnable(false); wall->getPhysicsBody()->setGroup(1); //组编号 /**一个body的CategoryBitmask和另一个body的ContactTestBitmask的逻辑与的结果不等于0时,接触事件将被发出,否则不发送。 *一个body的CategoryBitmask和另一个body的CollisionBitmask的逻辑与结果不等于0时,他们将碰撞,否则不碰撞 */ // wall->getPhysicsBody()->setCategoryBitmask(0x03);// 0011 碰撞系数编号 // wall->getPhysicsBody()->setContactTestBitmask(0x03);// 0001 碰撞检测编号 // wall->getPhysicsBody()->setCollisionBitmask(0x01);// 0001 碰撞编号 wall->setPosition(VisibleRect::center()); //位置可见区域中心 this->addChild(wall); //多纳的头 auto tou = Sprite::create(shizi_tou_png); // tou->setPhysicsBody(PhysicsBody::createCircle(271, PhysicsMaterial(1000.1f, 0.0f, 1.0f)));//添加半径为271动态圆形刚体 并赋予材质密度1000.1f 反弹力0.0f 摩擦力1.0f auto toubody = PEShapeCache::getInstance()->getPhysicsBodyByName("shizi_tou"); tou->setPhysicsBody(toubody); tou->getPhysicsBody()->setTag(DRAG_BODYS_TAG);//给刚体设置标签 tou->getPhysicsBody()->setMass(0.1);//刚体设置质量 tou->getPhysicsBody()->setGroup(2);//刚体组编号 tou->getPhysicsBody()->setCategoryBitmask(0x01); // 0001 tou->getPhysicsBody()->setContactTestBitmask(0x01); // 0001 tou->getPhysicsBody()->setCollisionBitmask(0x01); // 0001 // tou->getPhysicsBody()->setDynamic(false); 动态刚体是可以设置为静态 tou->getPhysicsBody()->setRotationEnable(false); //设置不可旋转刚体 碰撞后也不会旋转刚体 // tou->getPhysicsBody()->setGravityEnable(false);//设置是否接受重力影响 tou->getPhysicsBody()->setLinearDamping(3.0f); //设置线性阻尼系数 理论是0-1 但是可以大于1 值越大惯性越小 this->addChild(tou); tou->setPosition(VisibleRect::center()); auto touyingzi = Node::create(); touyingzi->setPhysicsBody(PhysicsBody::createCircle(271, PhysicsMaterial(1000.1f, 0.0f, 1.0f))); touyingzi->getPhysicsBody()->setTag(DRAG_BODYS_TAG_Y); //多纳的身子 //PhysicsShapePolygon 是通过点数组来构建不规则的凸多边形;用工具PhysicsEditor 编辑shap 让后导出Chipmunk 格式的plist 中的数据 注:PhysicsEditor Relative为锚点Anchor 设置为cocos默认值(0.5,0.5)才行 , auto shengzi = Sprite::create(shizi_shenzi_png); // auto shengzibody = PhysicsBody::create(); // Point vert1[3] = {Point(109.50000, 71.00000), Point(14.00000, 77.00000), Point(117.50000, 147.00000)}; // shengzibody->addShape(PhysicsShapePolygon::create(vert1, 3, PhysicsMaterial(0.1f, 0.0f, 1.0f))); // Point vert2[6] = {Point(-130.50000, -154.00000), Point(-120.50000, 46.00000), Point(-67.50000, 102.00000), Point(14.00000, 77.00000), Point(-4.00000, -93.00000), Point(-63.00000, -178.50000)}; // shengzibody->addShape(PhysicsShapePolygon::create(vert2, 6, PhysicsMaterial(0.1f, 0.0f, 1.0f))); // Point vert3[6] = {Point(138.50000, 18.00000), Point(110.50000, -177.00000), Point(51.50000, -175.00000), Point(-4.00000, -93.00000), Point(14.00000, 77.00000), Point(109.50000, 71.00000)}; // shengzibody->addShape(PhysicsShapePolygon::create(vert3, 6, PhysicsMaterial(0.1f, 0.0f, 1.0f))); // Point vert4[4] = {Point(-67.50000, 102.00000), Point(-55.00000, 172.50000), Point(-54.00000, 172.50000), Point(14.00000, 77.00000)}; // shengzibody->addShape(PhysicsShapePolygon::create(vert4, 4, PhysicsMaterial(0.1f, 0.0f, 1.0f))); auto shengzibody = PEShapeCache::getInstance()->getPhysicsBodyByName("shizi_shenzi"); shengzi->setPhysicsBody(shengzibody); shengzibody->setTag(DRAG_BODYS_TAG1); shengzibody->setRotationEnable(false); shengzibody->setGroup(2); shengzibody->setMass(0.1); shengzibody->setCategoryBitmask(0x02); //0010 shengzibody->setContactTestBitmask(0x02); //0010 shengzibody->setCollisionBitmask(0x02); //0010 shengzibody->setLinearDamping(3.0f); this->addChild(shengzi); shengzi->setPosition(VisibleRect::bottom() - Point(0, -300)); // auto contactListener = EventListenerPhysicsContactWithBodies::create(tou->getPhysicsBody(), shengzi->getPhysicsBody()); // contactListener->onContactBegin = CC_CALLBACK_1(HelloWorld::onContactBegin, this); // _eventDispatcher->addEventListenerWithSceneGraphPriority(contactListener, this); //多纳的头 auto b1 = Sprite::create(shizi_youshou_png); b1->setPhysicsBody(PEShapeCache::getInstance()->getPhysicsBodyByName("shizi_youshou")); b1->setPosition(VisibleRect::center()+Point(300,0)); b1->getPhysicsBody()->setTag(1); b1->getPhysicsBody()->setRotationEnable(false); this->addChild(b1); auto b2 = Sprite::create(shizi_zuoshou_png); b2->setPhysicsBody(PEShapeCache::getInstance()->getPhysicsBodyByName("shizi_zuoshou")); b2->setPosition(VisibleRect::center()-Point(300,0)); b2->getPhysicsBody()->setRotationEnable(false); b2->getPhysicsBody()->setTag(1); this->addChild(b2); // LabelTTF auto label2 = LabelTTF::create("多纳小狮子爱学习", "Arial", 64); label2->setPhysicsBody(PhysicsBody::createBox(label2->getBoundingBox().size, PhysicsMaterial(0.1f, 0.0f, 1.0f))); label2->getPhysicsBody()->setTag(1); // label2->getPhysicsBody()->setRotationEnable(false); label2->setPosition(VisibleRect::center()+Point(0,300)); addChild(label2, 0); PEShapeCache::getInstance()->removeBodysWithWithFile(buttonsbodys_plist); //注册碰撞检测监听 auto contactListener1 = EventListenerPhysicsContact::create(); contactListener1->onContactBegin = CC_CALLBACK_1(HelloWorld::onContactBegin, this); contactListener1->onContactPostSolve = CC_CALLBACK_2(HelloWorld::onContactPostSolve, this); _eventDispatcher->addEventListenerWithSceneGraphPriority(contactListener1, this); }
void CollisionMesh::loadImpl (void) { APP_ASSERT(masterShape==NULL); Ogre::DataStreamPtr file; try { file = Ogre::ResourceGroupManager::getSingleton().openResource(name.substr(1), "GRIT"); } catch (Ogre::Exception &e) { GRIT_EXCEPT(e.getDescription()); } std::string ext = name.substr(name.length()-5); uint32_t fourcc = 0; for (int i=0 ; i<4 ; ++i) { unsigned char c; file->read(&c, 1); fourcc |= c << (i*8); } file->seek(0); std::string dir = grit_dirname(name); const btVector3 ZV(0,0,0); const btQuaternion ZQ(0,0,0,1); bool compute_inertia = false; bool is_static = false; if (fourcc==0x4c4f4342) { //BCOL Ogre::MemoryDataStreamPtr mem = Ogre::MemoryDataStreamPtr(OGRE_NEW Ogre::MemoryDataStream(name,file)); BColFile &bcol = *reinterpret_cast<BColFile*>(mem->getPtr()); is_static = bcol.mass == 0.0f; // static masterShape = new btCompoundShape(); BColMaterialMap mmap(dir,name); for (unsigned i=0 ; i<bcol.hullNum ; ++i) { BColHull &p = *bcol.hulls(i); btConvexHullShape *s2 = new btConvexHullShape(); s2->setMargin(p.margin); for (unsigned j=0 ; j<p.vertNum ; ++j) { BColVert &v = *p.verts(j); s2->addPoint(btVector3(v.x, v.y, v.z)); } masterShape->addChildShape(btTransform(ZQ,ZV), s2); partMaterials.push_back(mmap(p.mat.name())); } for (unsigned i=0 ; i<bcol.boxNum ; ++i) { BColBox &p = *bcol.boxes(i); btBoxShape *s2 = new btBoxShape(btVector3(p.dx/2,p.dy/2,p.dz/2)); s2->setMargin(p.margin); masterShape->addChildShape(btTransform(btQuaternion(p.qx,p.qy,p.qz,p.qw), btVector3(p.px,p.py,p.pz)), s2); partMaterials.push_back(mmap(p.mat.name())); } for (unsigned i=0 ; i<bcol.cylNum ; ++i) { BColCyl &p = *bcol.cyls(i); btCylinderShape *s2 = new btCylinderShapeZ(btVector3(p.dx/2,p.dy/2,p.dz/2)); s2->setMargin(p.margin); masterShape->addChildShape(btTransform(btQuaternion(p.qx,p.qy,p.qz,p.qw), btVector3(p.px,p.py,p.pz)), s2); partMaterials.push_back(mmap(p.mat.name())); } for (unsigned i=0 ; i<bcol.coneNum ; ++i) { BColCone &p = *bcol.cones(i); btConeShape *s2 = new btConeShapeZ(p.radius,p.height); s2->setMargin(p.margin); masterShape->addChildShape(btTransform(btQuaternion(p.qx,p.qy,p.qz,p.qw), btVector3(p.px,p.py,p.pz)), s2); partMaterials.push_back(mmap(p.mat.name())); } for (unsigned i=0 ; i<bcol.planeNum ; ++i) { BColPlane &p = *bcol.planes(i); btStaticPlaneShape *s2 = new btStaticPlaneShape(btVector3(p.nx,p.ny,p.nz),p.d); masterShape->addChildShape(btTransform(ZQ,ZV), s2); partMaterials.push_back(mmap(p.mat.name())); } for (unsigned i=0 ; i<bcol.sphereNum ; ++i) { BColSphere &p = *bcol.spheres(i); btSphereShape *s2 = new btSphereShape(p.radius); masterShape->addChildShape(btTransform(ZQ, btVector3(p.px,p.py,p.pz)), s2); partMaterials.push_back(mmap(p.mat.name())); } if (bcol.triMeshFaceNum > 0) { bcolVerts.resize(bcol.triMeshVertNum); bcolFaces.resize(bcol.triMeshFaceNum); memcpy(&bcolVerts[0], bcol.triMeshVerts(0), bcol.triMeshVertNum * sizeof(BColVert)); memcpy(&bcolFaces[0], bcol.triMeshFaces(0), bcol.triMeshFaceNum * sizeof(BColFace)); faceMaterials.reserve(bcol.triMeshFaceNum); int counter = 0; float accum_area = 0; for (unsigned i=0 ; i<bcol.triMeshFaceNum ; ++i) { BColFace &face = *bcol.triMeshFaces(i); PhysicalMaterial *mat = mmap(face.mat.name()); faceMaterials.push_back(mat); CollisionMesh::ProcObjFace po_face(to_v3(bcolVerts[face.v1]), to_v3(bcolVerts[face.v2]), to_v3(bcolVerts[face.v3])); procObjFaceDB[mat->id].faces.push_back(po_face); float area = (po_face.AB.cross(po_face.AC)).length(); APP_ASSERT(area>=0); procObjFaceDB[mat->id].areas.push_back(area); procObjFaceDB[mat->id].totalArea += area; if (++counter = 10) { counter = 0; accum_area = 0; procObjFaceDB[mat->id].areas10.push_back(accum_area); } accum_area += area; } btTriangleIndexVertexArray *v = new btTriangleIndexVertexArray( bcolFaces.size(), reinterpret_cast<int*>(&(bcolFaces[0].v1)), sizeof(BColFace), bcolVerts.size(), &(bcolVerts[0].x), sizeof(BColVert)); if (is_static) { btBvhTriangleMeshShape *tm = new btBvhTriangleMeshShape(v,true,true); tm->setMargin(bcol.triMeshMargin); btTriangleInfoMap* tri_info_map = new btTriangleInfoMap(); tri_info_map->m_edgeDistanceThreshold = bcol.triMeshEdgeDistanceThreshold; btGenerateInternalEdgeInfo(tm,tri_info_map); masterShape->addChildShape(btTransform::getIdentity(), tm); } else { // skip over dynamic trimesh } } setMass(bcol.mass); setLinearDamping(bcol.linearDamping); setAngularDamping(bcol.angularDamping); setLinearSleepThreshold(bcol.linearSleepThreshold); setAngularSleepThreshold(bcol.angularSleepThreshold); setCCDMotionThreshold(bcol.ccdMotionThreshold); setCCDSweptSphereRadius(bcol.ccdSweptSphereRadius); setInertia(Vector3(bcol.inertia[0],bcol.inertia[1],bcol.inertia[2])); compute_inertia = !bcol.inertiaProvided; } else if (fourcc==0x4c4f4354) { //TCOL ProxyStreamBuf proxy(file); std::istream stream(&proxy); quex::tcol_lexer qlex(&stream); TColFile tcol; parse_tcol_1_0(name,&qlex,tcol); is_static = tcol.mass == 0.0f; // static masterShape = new btCompoundShape(); if (tcol.usingCompound) { TColCompound &c = tcol.compound; for (size_t i=0 ; i<c.hulls.size() ; ++i) { const TColHull &h = c.hulls[i]; btConvexHullShape *s2 = new btConvexHullShape(); s2->setMargin(h.margin); for (unsigned j=0 ; j<h.vertexes.size() ; ++j) { const Vector3 &v = h.vertexes[j]; s2->addPoint(to_bullet(v)); } masterShape->addChildShape(btTransform(ZQ,ZV), s2); partMaterials.push_back(phys_mats.getMaterial(dir,name,h.material)); } for (size_t i=0 ; i<c.boxes.size() ; ++i) { const TColBox &b = c.boxes[i]; /* implement with hulls btConvexHullShape *s2 = new btConvexHullShape(); s2->addPoint(btVector3(-b.dx/2+b.margin, -b.dy/2+b.margin, -b.dz/2+b.margin)); s2->addPoint(btVector3(-b.dx/2+b.margin, -b.dy/2+b.margin, b.dz/2-b.margin)); s2->addPoint(btVector3(-b.dx/2+b.margin, b.dy/2-b.margin, -b.dz/2+b.margin)); s2->addPoint(btVector3(-b.dx/2+b.margin, b.dy/2-b.margin, b.dz/2-b.margin)); s2->addPoint(btVector3( b.dx/2-b.margin, -b.dy/2+b.margin, -b.dz/2+b.margin)); s2->addPoint(btVector3( b.dx/2-b.margin, -b.dy/2+b.margin, b.dz/2-b.margin)); s2->addPoint(btVector3( b.dx/2-b.margin, b.dy/2-b.margin, -b.dz/2+b.margin)); s2->addPoint(btVector3( b.dx/2-b.margin, b.dy/2-b.margin, b.dz/2-b.margin)); */ btBoxShape *s2 =new btBoxShape(btVector3(b.dx/2,b.dy/2,b.dz/2)); s2->setMargin(b.margin); masterShape->addChildShape(btTransform(btQuaternion(b.qx,b.qy,b.qz,b.qw), btVector3(b.px,b.py,b.pz)), s2); partMaterials.push_back(phys_mats.getMaterial(dir,name,b.material)); } for (size_t i=0 ; i<c.cylinders.size() ; ++i) { const TColCylinder &cyl = c.cylinders[i]; btCylinderShape *s2 = new btCylinderShapeZ(btVector3(cyl.dx/2,cyl.dy/2,cyl.dz/2)); s2->setMargin(cyl.margin); masterShape->addChildShape( btTransform(btQuaternion(cyl.qx,cyl.qy,cyl.qz,cyl.qw), btVector3(cyl.px,cyl.py,cyl.pz)), s2); partMaterials.push_back(phys_mats.getMaterial(dir,name,cyl.material)); } for (size_t i=0 ; i<c.cones.size() ; ++i) { const TColCone &cone = c.cones[i]; btConeShapeZ *s2 = new btConeShapeZ(cone.radius,cone.height); s2->setMargin(cone.margin); masterShape->addChildShape( btTransform(btQuaternion(cone.qx,cone.qy,cone.qz,cone.qw), btVector3(cone.px,cone.py,cone.pz)), s2); partMaterials.push_back(phys_mats.getMaterial(dir,name,cone.material)); } for (size_t i=0 ; i<c.planes.size() ; ++i) { const TColPlane &p = c.planes[i]; btStaticPlaneShape *s2 = new btStaticPlaneShape(btVector3(p.nx,p.ny,p.nz),p.d); masterShape->addChildShape(btTransform(ZQ,ZV), s2); partMaterials.push_back(phys_mats.getMaterial(dir,name,p.material)); } for (size_t i=0 ; i<c.spheres.size() ; ++i) { const TColSphere &sp = c.spheres[i]; btSphereShape *s2 = new btSphereShape(sp.radius); masterShape->addChildShape(btTransform(ZQ, btVector3(sp.px,sp.py,sp.pz)), s2); partMaterials.push_back(phys_mats.getMaterial(dir,name,sp.material)); } } if (tcol.usingTriMesh) { TColTriMesh &t = tcol.triMesh; std::swap(verts, t.vertexes); std::swap(faces, t.faces); faceMaterials.reserve(faces.size()); int counter = 0; float accum_area = 0; for (TColFaces::const_iterator i=faces.begin(), i_=faces.end() ; i!=i_ ; ++i) { //optimisation possible here by changing the TCol struct to be more liek what //bullet wants, and then re-using memory PhysicalMaterial *mat = phys_mats.getMaterial(dir,name,i->material); faceMaterials.push_back(mat); CollisionMesh::ProcObjFace po_face(verts[i->v1], verts[i->v2], verts[i->v3]); procObjFaceDB[mat->id].faces.push_back(po_face); float area = (po_face.AB.cross(po_face.AC)).length(); APP_ASSERT(area>=0); procObjFaceDB[mat->id].areas.push_back(area); procObjFaceDB[mat->id].totalArea += area; if (++counter = 10) { counter = 0; accum_area = 0; procObjFaceDB[mat->id].areas10.push_back(accum_area); } accum_area += area; } btTriangleIndexVertexArray *v = new btTriangleIndexVertexArray( faces.size(), &(faces[0].v1), sizeof(TColFace), verts.size(), &(verts[0].x), sizeof(Vector3)); if (is_static) { btBvhTriangleMeshShape *tm = new btBvhTriangleMeshShape(v,true,true); tm->setMargin(t.margin); btTriangleInfoMap* tri_info_map = new btTriangleInfoMap(); tri_info_map->m_edgeDistanceThreshold = t.edgeDistanceThreshold; btGenerateInternalEdgeInfo(tm,tri_info_map); masterShape->addChildShape(btTransform::getIdentity(), tm); } else { // Skip over dynamic trimesh } } setMass(tcol.mass); setInertia(Vector3(tcol.inertia_x,tcol.inertia_y,tcol.inertia_z)); setLinearDamping(tcol.linearDamping); setAngularDamping(tcol.angularDamping); setLinearSleepThreshold(tcol.linearSleepThreshold); setAngularSleepThreshold(tcol.angularSleepThreshold); setCCDMotionThreshold(tcol.ccdMotionThreshold); setCCDSweptSphereRadius(tcol.ccdSweptSphereRadius); compute_inertia = !tcol.hasInertia; } else { GRIT_EXCEPT("Collision mesh \""+name+"\" seems to be corrupt."); } if (is_static) { setInertia(Vector3(0,0,0)); } else { if (faceMaterials.size() > 0) { CERR << "While loading \"" + name + "\": Dynamic trimesh not supported." << std::endl; } if (compute_inertia) { btVector3 i; masterShape->calculateLocalInertia(mass,i); setInertia(from_bullet(i)); } } }
bool GameLayer::init(){ if(Layer::init()) { //get the origin point of the X-Y axis, and the visiable size of the screen Size visiableSize = Director::getInstance()->getVisibleSize(); Point origin = Director::getInstance()->getVisibleOrigin(); this->gameStatus = GAME_STATUS_READY; this->score = 0; // Add the bird this->bird = BirdSprite::getInstance(); this->bird->createBird(); PhysicsBody *body = PhysicsBody::create(); body->addShape(PhysicsShapeCircle::create(BIRD_RADIUS)); body->setCategoryBitmask(ColliderTypeBird); body->setCollisionBitmask(ColliderTypeLand & ColliderTypePip | ColliderTypeBall); body->setContactTestBitmask(ColliderTypeLand | ColliderTypePip | ColliderTypeBall); body->setDynamic(true); body->setLinearDamping(0.0f); body->setGravityEnable(false); this->bird->setPhysicsBody(body); this->bird->setPosition(origin.x + visiableSize.width*1/3 - 5,origin.y + visiableSize.height/2 + 5); this->bird->idle(); this->addChild(this->bird); /* //初始化加速粒子 accelerateParticle = ParticleSystemQuad::create("particleImpact.plist"); accelerateParticle->setScale(0.5f); accelerateParticle->setPosition(0,0); addChild(accelerateParticle); */ accelerateParticle = NULL; pipSpeed = 2; /* //闪亮 Blink *blink = Blink::create(5.0f, 10); bird->runAction(blink); */ //Ball this->ball = Sprite::create("ball.png"); PhysicsBody *ballbody = PhysicsBody::create(); ballbody->addShape(PhysicsShapeCircle::create(BIRD_RADIUS+5)); ballbody->setCategoryBitmask(ColliderTypeBall); ballbody->setCollisionBitmask(ColliderTypePip | ColliderTypeLand); ballbody->setContactTestBitmask(ColliderTypePip | ColliderTypeLand); ballbody->setDynamic(true); ballbody->setLinearDamping(0.0f); ballbody->setGravityEnable(false); ball->setPhysicsBody(ballbody); // static Shaky3D* create(float duration, const Size& gridSize, int range, bool shakeZ); ball->setPosition(bird->getPositionX(),bird->getPositionY()+30); ball->setTag(100); // addChild(ball); BallisTouch = false; //BallName ballName = Sprite::create("BallWithHoney.png"); ballName->setPosition(ball->getPositionX(),ball->getPositionY()+40); //addChild(ballName); // Add the ground this->groundNode = Node::create(); float landHeight = BackgroundLayer::getLandHeight(); auto groundBody = PhysicsBody::create(); groundBody->addShape(PhysicsShapeBox::create(Size(288, landHeight))); groundBody->setDynamic(false); groundBody->setLinearDamping(0.0f); groundBody->setCategoryBitmask(ColliderTypeLand); groundBody->setCollisionBitmask(ColliderTypeBird | ColliderTypeBall); groundBody->setContactTestBitmask(ColliderTypeBird | ColliderTypeLand); this->groundNode->setPhysicsBody(groundBody); this->groundNode->setPosition(144, landHeight/2); this->addChild(this->groundNode); // init land this->landSpite1 = Sprite::createWithSpriteFrame(AtlasLoader::getInstance()->getSpriteFrameByName("land")); this->landSpite1->setAnchorPoint(Point::ZERO); this->landSpite1->setPosition(Point::ZERO); this->addChild(this->landSpite1, 30); this->landSpite2 = Sprite::createWithSpriteFrame(AtlasLoader::getInstance()->getSpriteFrameByName("land")); this->landSpite2->setAnchorPoint(Point::ZERO); this->landSpite2->setPosition(this->landSpite1->getContentSize().width-2.0f,0); this->addChild(this->landSpite2, 30); shiftLand = schedule_selector(GameLayer::scrollLand); this->schedule(shiftLand, 0.01f); this->scheduleUpdate(); auto contactListener = EventListenerPhysicsContact::create(); contactListener->onContactBegin = CC_CALLBACK_1(GameLayer::onContactBegin, this); this->getEventDispatcher()->addEventListenerWithSceneGraphPriority(contactListener, this); return true; }else { return false; } }
void PhysicsBody::setDamping (Real32 linear_scale, Real32 angular_scale) { setLinearDamping(linear_scale); setAngularDamping(angular_scale); }
//Damping void PhysicsBody::setDampingDefaults (void) { dBodySetDampingDefaults(_BodyID); setLinearDamping(dBodyGetLinearDamping(_BodyID)); setAngularDamping(dBodyGetAngularDamping(_BodyID)); }
bool GameLayer::init() { if (!Layer::init()) return false; // Welcome Message Size visiableSize = Director::getInstance()->getVisibleSize(); Vec2 origin = Director::getInstance()->getVisibleOrigin(); // screen background auto screenBackground = Sprite::create("screen_background.png"); screenBackground->setAnchorPoint(Point::ZERO); screenBackground->setPosition(Vec2(0, 0)); this->addChild(screenBackground); // sprite ⇨ mosquito mosquito = Sprite::create("mosquito.png"); mosquito->setPosition(Vec2(30, visiableSize.height - 300)); mosquito->setScale(0.1 * ( visiableSize.width / mosquito->getBoundingBox().size.width)); this->addChild(mosquito); //bug->runAction(this->create(6, bug->getPosition(), Vec2(visiableSize.width - 30, visiableSize.height - 300), 100)); mosquito->runAction(Spawn::create(RotateBy::create(5, 1080), this->create(5, mosquito->getPosition(),Vec2(visiableSize.width - 30, visiableSize.height - 300), 100), NULL)); PhysicsBody *body = PhysicsBody::createCircle(BUG_RADIUS); body->addShape(PhysicsShapeCircle::create(BUG_RADIUS)); body->setDynamic(true); body->setLinearDamping(0.0f); body->setGravityEnable(false); body->setMass(1.0f); body->setContactTestBitmask(0xFFFFFFFF); this->mosquito->setPhysicsBody(body); // ************************************************************************ // // MotionStreakを作成 pStreak = MotionStreak::create(1.0, 1.0f, 3.0f, Color3B::GREEN, "suspend.png"); addChild(pStreak); this->groundNode = Node::create(); //イベントリスナー作成 auto listener = EventListenerTouchOneByOne::create(); //タッチ開始時 listener->onTouchBegan = [this](Touch* touch, Event* event) { Point pos = this->convertTouchToNodeSpace(touch); this->pStreak->setPosition(pos); auto groundBody = PhysicsBody::createBox(Size(4, pos.y)); groundBody->addShape(PhysicsShapeBox::create(Size(4, pos.y))); groundBody->setDynamic(false); groundBody->setLinearDamping(0.0f); groundBody->setMass(1.0f); groundBody->setContactTestBitmask(0xFFFFFFFF); this->groundNode->setPhysicsBody(groundBody); this->groundNode->setPosition(pos.x, pos.y); this->addChild(this->groundNode); return true; }; //タッチ移動時 listener->onTouchMoved = [this](Touch* touch, Event* event) { Point pos = this->convertTouchToNodeSpace(touch); this->pStreak->setPosition(pos); }; //ディスパッチャに登録 Director::getInstance()->getEventDispatcher()->addEventListenerWithFixedPriority(listener, 100); // *************************************************************************************** // // sprite ⇨ suspend (init for invisible) suspendBackground = Sprite::create("suspend_background.png"); suspendBackground->setAnchorPoint(Point::ZERO); suspendBackground->setPosition(Vec2(0, 0 + 40)); suspendBackground->setScale(visiableSize.width / suspendBackground->getBoundingBox().size.width, (visiableSize.height - 40)/ suspendBackground->getBoundingBox().size.height); suspendBackground->setTag(2009); suspendBackground->setVisible(false); this->addChild(suspendBackground); //进入暂停 auto suspendBtn = Sprite::create("suspend.png"); auto menuSuspendItem = MenuItemSprite::create(suspendBtn, suspendBtn, NULL, CC_CALLBACK_1(GameLayer::menuSuspendCallback, this)); menuSuspendItem->setPosition(Vec2(visiableSize.width - suspendBtn->getBoundingBox().size.width - 20, visiableSize.height - suspendBtn->getBoundingBox().size.height - 20)); auto menu = Menu::create(menuSuspendItem, NULL); menu->setPosition(Point::ZERO); this->addChild(menu, 3); // suspend close button auto closeButton = Sprite::create("exit.png"); MenuItem *menuCloseItem = MenuItemSprite::create(closeButton, closeButton, NULL, CC_CALLBACK_1(GameLayer::menuSuspendCloseCallback, this)); menuCloseItem->setPosition(Vec2(245, 128)); pauseMenu = Menu::create( menuCloseItem, NULL); pauseMenu->setPosition(Point::ZERO); pauseMenu->setVisible(false); this->addChild(pauseMenu, 4); schedule(schedule_selector(GameLayer::update), 2.0f); auto contactListener = EventListenerPhysicsContact::create(); contactListener->onContactBegin = CC_CALLBACK_1(GameLayer::onContactBegin, this); this->getEventDispatcher()->addEventListenerWithSceneGraphPriority(contactListener, this); return true; }
bool GameLayer::init(){ if(Layer::init()) { //get the origin point of the X-Y axis, and the visiable size of the screen Size visiableSize = Director::getInstance()->getVisibleSize(); Point origin = Director::getInstance()->getVisibleOrigin(); this->gameStatus = GAME_STATUS_READY; this->score = 0; // Add the bird this->bird = BirdSprite::getInstance(); this->bird->createBird(); PhysicsBody *body = PhysicsBody::create(); body->addShape(PhysicsShapeCircle::create(BIRD_RADIUS)); //ÅöײÉèÖà body->setCategoryBitmask(ColliderTypeBird); body->setCollisionBitmask(ColliderTypeLand | ColliderTypePip); body->setContactTestBitmask(ColliderTypeLand | ColliderTypePip); body->setDynamic(true); body->setLinearDamping(0.0f); body->setGravityEnable(false); this->bird->setPhysicsBody(body); this->bird->setPosition(origin.x + visiableSize.width*1/3 - 5,origin.y + visiableSize.height/2 + 5); this->bird->idle(); this->addChild(this->bird); // Add the ground this->groundNode = Node::create(); float landHeight = BackgroundLayer::getLandHeight(); auto groundBody = PhysicsBody::create(); groundBody->addShape(PhysicsShapeBox::create(Size(288, landHeight))); groundBody->setDynamic(false); groundBody->setLinearDamping(0.0f); //ÅöײÉèÖà groundBody->setCategoryBitmask(ColliderTypeLand); groundBody->setCollisionBitmask(ColliderTypeBird); groundBody->setContactTestBitmask(ColliderTypeBird); this->groundNode->setPhysicsBody(groundBody); this->groundNode->setPosition(144, landHeight/2); this->addChild(this->groundNode); // init land this->landSpite1 = Sprite::createWithSpriteFrame(AtlasLoader::getInstance()->getSpriteFrameByName("land")); this->landSpite1->setAnchorPoint(Point::ZERO); this->landSpite1->setPosition(Point::ZERO); this->addChild(this->landSpite1, 30); this->landSpite2 = Sprite::createWithSpriteFrame(AtlasLoader::getInstance()->getSpriteFrameByName("land")); this->landSpite2->setAnchorPoint(Point::ZERO); this->landSpite2->setPosition(this->landSpite1->getContentSize().width-2.0f,0); this->addChild(this->landSpite2, 30); shiftLand = schedule_selector(GameLayer::scrollLand); this->schedule(shiftLand, 0.01f); this->scheduleUpdate(); auto contactListener = EventListenerPhysicsContact::create(); contactListener->onContactBegin = CC_CALLBACK_1(GameLayer::onContactBegin, this); this->getEventDispatcher()->addEventListenerWithSceneGraphPriority(contactListener, this); this->dialogLayer = nullptr; return true; }else { return false; } }
void CIrrOdeWorld::initPhysics() { if (m_bPhysicsInitialized) return; m_iNodesInitialized=0; CIrrOdeSceneNode::initPhysics(); m_iWorldId=m_pOdeDevice->worldCreate(); m_iJointGroupId=m_pOdeDevice->jointGroupCreate(0); if (!m_pWorldSpace) m_pWorldSpace=new CIrrOdeSpace(this,m_pSceneManager); if (m_pWorldSpace!=NULL) m_pWorldSpace->initPhysics(); setLinearDamping (m_fDampingLinear ); setAngularDamping (m_fDampingAngular ); setLinearDampingThreshold (m_fDampingLinearThreshold ); setAngularDampingThreshold(m_fDampingAngularThreshold); setAutoDisableFlag (m_iAutoDisableFlag ); setAutoDisableLinearThreshold (m_fAutoDisableLinearThreshold ); setAutoDisableAngularThreshold(m_fAutoDisableAngularThreshold); setAutoDisableSteps (m_iAutoDisableSteps ); setAutoDisableTime (m_fAutoDisableTime ); setGravity(m_cGravity); if (m_fMaxAngularSpeed!=_DEFAULT_MAX_ANGULAR_SPEED) setMaxAngularSpeed(m_fMaxAngularSpeed); #ifdef _TRACE_INIT_PHYSICS printf("world created .. id=%i\n",(int)m_iWorldId); #endif irr::core::list<CIrrOdeSpace *>::Iterator s; for (s=m_pSpaces.begin(); s!=m_pSpaces.end(); s++) { #ifdef _TRACE_INIT_PHYSICS printf("CIrrOdeWorld::initPhysics: init space\n"); #endif CIrrOdeSpace *pSpace=(*s); pSpace->initPhysics(); } irr::core::list<CIrrOdeGeom *>::Iterator i; for (i=m_pGeoms.begin(); i!=m_pGeoms.end(); i++) { #ifdef _TRACE_INIT_PHYSICS printf("CIrrOdeWorld::initPhysics: init geom\n"); #endif CIrrOdeGeom *pGeom=(*i); pGeom->initPhysics(); } irr::core::list<CIrrOdeBody *>::Iterator b,ib2; for (b=m_pBodies.begin(); b!=m_pBodies.end(); b++) { #ifdef _TRACE_INIT_PHYSICS printf("CIrrOdeWorld::initPhysics: init body\n"); #endif CIrrOdeBody *b1=*b; b1->initPhysics(); } irr::core::list<irr::ode::IIrrOdeStepMotor *>::Iterator it; for (it=m_lStepMotors.begin(); it!=m_lStepMotors.end(); it++) (*it)->initPhysics(); m_bPhysicsInitialized = true; }