void PFMPlayer::reload() { if(_preset == NULL) return; for(int i=0;i<_preset->components.size();i++) { PFMComponent* component = _preset->components[i]; if(component->componentClass == "Sprite") { PFMSpriteComponent* spriteComponent = dynamic_cast<PFMSpriteComponent*>(component); PFMSprite* sprite = PFMSprite::createWithComponent(spriteComponent); Size size = sprite->getBoundingBox().size; PhysicsBody* physicsBody = PhysicsBody::createBox(sprite->getBoundingBox().size); physicsBody->setCollisionBitmask(0); physicsBody->setCategoryBitmask(PFMCollideMaskBitsPlayer); physicsBody->setContactTestBitmask(PFMCollideMaskBitsEnemyBullet | PFMCollideMaskBitsEnemy); setPhysicsBody(physicsBody); addChild(sprite); } else if(component->componentClass == "BulletGun") { PFMBulletGunComponent* bulletGunComponent = dynamic_cast<PFMBulletGunComponent*>(component); PFMBulletGun* bulletGun = PFMBulletGun::createWithComponent(bulletGunComponent); bulletGun->isHostByPlayer = true; bulletGun->isAutoShoot = true; addChild(bulletGun); } // else if([component isMemberOfClass:[AstMissleLauncherComponent class]]) // { // AstMissleLauncher* missleLauncher = [[AstMissleLauncher alloc]initWithSession:self.session]; // [self addNode:missleLauncher.rootNode]; // [missleLauncher setComponent:(AstMissleLauncherComponent*)component]; // } } }
PhysicsForceField::~PhysicsForceField() { for (auto bm : _gravitySources) { PhysicsBody* body = bm.first; body->release(); } }
bool PFMPlayer::onContactBegin(cocos2d::PhysicsContact &contact) { if(contact.getShapeA()->getBody() == getPhysicsBody() || contact.getShapeB()->getBody() == getPhysicsBody()) { PhysicsBody* other = contact.getShapeA()->getBody() == getPhysicsBody()?contact.getShapeB()->getBody() : contact.getShapeA()->getBody(); switch (other->getTag()) { case PFMPhysicsBodyTypeEnemyBullet: { PFMBullet* bullet = dynamic_cast<PFMBullet*>(other->getNode()); if(bullet != NULL) { health -= bullet->damage; } other->getOwner()->removeFromParentAndCleanup(true); break; } case PFMPhysicsBodyTypeEnemy: other->getOwner()->removeFromParentAndCleanup(true); break; default: break; } } return true; }
bool GameScene::onContactBegin(cocos2d::PhysicsContact &contact) { PhysicsBody *a = contact.getShapeA()->getBody(); PhysicsBody *b = contact.getShapeB()->getBody(); if ( (SNAKE_COLLISION_BITMASK == a->getCollisionBitmask() && FOOD_COLLISION_BITMASK == b->getCollisionBitmask()) || (SNAKE_COLLISION_BITMASK == b->getCollisionBitmask() && FOOD_COLLISION_BITMASK == a->getCollisionBitmask()) ) { srand(time(NULL)); auto random = rand() % 370 + 30; auto random2 = rand() % 270 + 30; auto moveTo = MoveTo::create(0, Vec2(random, random2)); food->runAction(moveTo); int tempX = snakeParts.back()->getPositionX(); int tempY = snakeParts.back()->getPositionY(); Sprite* tempSprite = Sprite::create("snake.png"); switch (direction) { case LEFT: tempSprite->setPosition(tempX + 10, tempY); break; case RIGHT: tempSprite->setPosition(tempX - 10, tempY); break; case UP: tempSprite->setPosition(tempX, tempY + 10); break; case DOWN: tempSprite->setPosition(tempX, tempY - 10); break; } this->addChild(tempSprite); snakeParts.push_back(tempSprite); } return true; }
void CW::CeilingTerrain::Init(void) { PhysicsBody* b = new PhysicsBody(); VerletPoint* V1 = new VerletPoint(0, 0); VerletPoint* V2 = new VerletPoint(60, 0); VerletPoint* V3 = new VerletPoint(60, 100); VerletPoint* V4 = new VerletPoint(0, 100); b->AddVertex(V1); b->AddVertex(V2); b->AddVertex(V3); b->AddVertex(V4); for (VerletPoint* p : b->Vertices) { p->IsStatic = true; } blocks.push_back(b); for (int i=0;i<20;++i) { AddBlock(); } }
PhysicsBody *PEShapeCache::getPhysicsBodyByName(const std::string name) { BodyDef *bd = bodyDefs.at(name); CCASSERT(bd != nullptr, "Body not found"); PhysicsBody *body = PhysicsBody::create(bd->mass, bd->momentum); body->setPositionOffset(bd->anchorPoint); for (auto fd : bd->fixtures) { if (fd->fixtureType == SHAPE_CIRCLE) { auto shape = PhysicsShapeCircle::create(fd->radius, PhysicsMaterial(0.0f, fd->elasticity, fd->friction), fd->center); shape->setGroup(fd->group); // shape->setCategoryBitmask(fd->collisionType); body->addShape(shape); } else if (fd->fixtureType == SHAPE_POLYGON) { for (auto polygon : fd->polygons) { auto shape = PhysicsShapePolygon::create(polygon->vertices, polygon->numVertices, PhysicsMaterial(0.0f, fd->elasticity, fd->friction), fd->center); shape->setGroup(fd->group); // shape->setCategoryBitmask(fd->collisionType); body->addShape(shape); } } } return body; }
void SceneFlyGame::addBlock(float) { int r = CCRANDOM_0_1() * 5; if (r == 0) { // 加砖头 r = CCRANDOM_0_1() * 6 + 4; Size size = Size(16, 16 * r); Node * node = Node::create(); addChild(node); node->setContentSize(size); for (int i = 0; i < r; ++i) { Sprite * sprite = Sprite::create("superMarioMap.png", Rect(1, 1, 16, 16)); node->addChild(sprite); sprite->setPosition(0, i * 16); sprite->setAnchorPoint(Vec2::ANCHOR_BOTTOM_LEFT); } node->setAnchorPoint(Vec2::ANCHOR_MIDDLE); PhysicsBody * body = PhysicsBody::createEdgeBox(size); node->setPhysicsBody(body); body->setContactTestBitmask(1); // 设置node的位置 r = CCRANDOM_0_1() * 2; node->setPositionX(winSize.width + 16); if (r == 0) node->setPositionY(size.height / 2); else node->setPositionY(winSize.height - size.height / 2); // 加入数组 m_blocks.pushBack(node); } }
void PhysicsWorld::removeBody(PhysicsBody* body) { if (body->getWorld() != this) { CCLOG("Physics Warnning: this body doesn't belong to this world"); return; } // destory the body's joints for (auto joint : body->_joints) { // set destroy param to false to keep the iterator available removeJoint(joint, false); PhysicsBody* other = (joint->getBodyA() == body ? joint->getBodyB() : body); other->removeJoint(joint); // test the distraction is delaied or not if (_delayRemoveJoints.size() > 0 && _delayRemoveJoints.back() == joint) { joint->_destoryMark = true; } else { delete joint; } } body->_joints.clear(); removeBodyOrDelay(body); _bodies.eraseObject(body); body->_world = nullptr; }
void Monster::joinToWorld(Node* parent) { Sprite* sp = Sprite::createWithSpriteFrameName(m_sModelPath.asString().c_str()); /* 创建刚体 */ PhysicsBody* body = PhysicsBody::createBox(sp->getContentSize()); body->setCategoryBitmask(1); // 0001 body->setCollisionBitmask(1); // 0001 body->setContactTestBitmask(1); // 0001 /* 精灵居中 */ sp->setPosition(Point(sp->getContentSize().width * 0.5f, sp->getContentSize().height * 0.5f)); /* 精灵作为Monster的表现,添加到Monster身上 */ this->addChild(sp); /* 设置怪物Tag类型 */ this->setTag(ObjectTag_Monster); /* 精灵作为Monster的表现,Monster本身没有大小,所以要设置一下大小 */ this->setContentSize(sp->getContentSize()); /* 刚体添加到Monster本身,而不是精灵身上 */ this->setPhysicsBody(body); /* 设置坐标 */ this->setPosition(Point(getiPosX(), getiPosY())); /* Monster加入到物理世界 */ parent->addChild(this); }
bool BaseDemo::onTouchBegan(Touch* touch, Event* event) { auto location = touch->getLocation(); auto shapeArr = _world->getShapes(location); PhysicsBody* body = nullptr; for(auto& obj : shapeArr) { if((obj->getBody()->getTag() & DRAG_BODYS_TAG) != 0) { body = obj->getBody(); break; } } if(body != nullptr) { Node* mouse = Node::create(); mouse->setPhysicsBody(PhysicsBody::create(PHYSICS_INFINITY, PHYSICS_INFINITY)); mouse->getPhysicsBody()->setDynamic(false); mouse->setPosition(location); this->addChild(mouse); PhysicsJointPin* joint = PhysicsJointPin::construct(mouse->getPhysicsBody(), body, location); joint->setMaxForce(5000.0f * body->getMass()); _world->addJoint(joint); _mouses.insert(std::make_pair(touch->getID(), mouse)); return true; } return false; }
bool PlayerComponent::onContactBegin(PhysicsContact& contact) { if (!is_endGame) { PhysicsBody *a = contact.getShapeB()->getBody(); if ((a->getCollisionBitmask() == OBSTACLE_ID) || (a->getCollisionBitmask() == SPIKESBORDER_ID)) { is_onTouch = false; is_fall = false; is_endGame = true; // display 'dialog box' this->getOwner()->addChild(MyDialogBox::create( { Label::create("Your Score:", "Calibri", 30), Label::create(StringUtils::toString(((ScoreCounterComponent*)this->getOwner()->getComponent(SCORECOUNTER_NAME))->getScore()), "Calibri", 120) }, { DialogBoxButton("TRY AGAIN", TextHAlignment::LEFT, CC_CALLBACK_1(GameScene::goToGameScene, ((GameScene*)this->getOwner()))), DialogBoxButton("BACK TO\n MAIN MENU", TextHAlignment::RIGHT, CC_CALLBACK_1(GameScene::goToMainMenuScene, ((GameScene*)this->getOwner()))) } ), 10); } } return false; }
void Physics::step(void) { dynamicWorld->stepSimulation(1.f/60.f); graphics->animate(); int numManifolds = dynamicWorld->getDispatcher()->getNumManifolds(); for (int i = 0; i < numManifolds; i++) { btPersistentManifold* contactManifold = dynamicWorld->getDispatcher()->getManifoldByIndexInternal(i); btCollisionObject* obA = static_cast<btCollisionObject*>(contactManifold->getBody0()); btCollisionObject* obB = static_cast<btCollisionObject*>(contactManifold->getBody1()); btBroadphaseProxy* obA_proxy = obA->getBroadphaseHandle(); btBroadphaseProxy* obB_proxy = obB->getBroadphaseHandle(); if (obA_proxy->m_collisionFilterGroup & obB_proxy->m_collisionFilterMask) { if (obA_proxy->m_collisionFilterGroup == COL_PENGUIN && obB_proxy->m_collisionFilterGroup == COL_KILLBOX) { PhysicsBody* object = reinterpret_cast<PhysicsBody*>(obA->getUserPointer()); resetObject(object); } else if (obA_proxy->m_collisionFilterGroup == COL_PENGUIN && obB_proxy->m_collisionFilterGroup == COL_GOAL) { nextStage(); graphics->playSound(2); } else if (obA_proxy->m_collisionFilterGroup == COL_PENGUIN && obB_proxy->m_collisionFilterGroup == COL_CHECKPOINT) { btVector3 checkpoint2 = obB->getWorldTransform().getOrigin(); btBoxShape* shape = reinterpret_cast<btBoxShape*>(obB->getCollisionShape()); checkpoint2 += btVector3(0, shape->getHalfExtentsWithoutMargin().y(), 0); checkpoint2 += btVector3(0, 25, 0); PhysicsBody* object = reinterpret_cast<PhysicsBody*>(obA->getUserPointer()); btRigidBody* body = object->getBody(); btVector3 translate = body->getCenterOfMassPosition(); if (checkpoint2 != checkpoint && translate.y() >= checkpoint2.y()) { graphics->playSound(1); checkpoint = checkpoint2; } } } } }
void CW::CeilingTerrain::AddBlock(void) { PhysicsBody* b = new PhysicsBody(); int dif = rand() % 10; if (rand() % 10 < 4) dif *= -1; if (blocks[blocks.size() -1]->Vertices[2]->Position.y > 200) dif = -4; if (blocks[blocks.size() -1]->Vertices[2]->Position.y < 50) dif = 4; VerletPoint* V1 = new VerletPoint(blocks[blocks.size() -1]->Vertices[1]->Position.x, 0); VerletPoint* V2 = new VerletPoint(blocks[blocks.size() -1]->Vertices[1]->Position.x + 60, 0); VerletPoint* V3 = new VerletPoint(blocks[blocks.size() -1]->Vertices[1]->Position.x + 60, blocks[blocks.size() -1]->Vertices[2]->Position.y + dif); VerletPoint* V4 = new VerletPoint(blocks[blocks.size() -1]->Vertices[1]->Position.x, blocks[blocks.size() -1]->Vertices[2]->Position.y); b->AddVertex(V1); b->AddVertex(V2); b->AddVertex(V3); b->AddVertex(V4); blocks.push_back(b); }
bool HelloWorld::onTouchBegan(cocos2d::Touch *touch, cocos2d::Event *event) { CCLOG("%s", "touch"); auto location = touch->getLocation(); auto arr = _scene->getPhysicsWorld()->getShapes(location);//从物理世界得到多边形 PhysicsBody *body = nullptr; for (auto &obj : arr) { if ((obj->getBody()->getTag() & DRAG_BODYS_TAG) != 0) //得到刚体 { body = obj->getBody(); break; } } if (body != nullptr) { //创建一个刚体 Node *mouse = Node::create(); mouse->setPhysicsBody(PhysicsBody::create(PHYSICS_INFINITY, PHYSICS_INFINITY)); mouse->getPhysicsBody()->setDynamic(false); mouse->setPosition(location); this->addChild(mouse); body->setLinearDamping(0.0f); //用图钉关节与点中刚体绑定 赋予力 可以拖动 PhysicsJointPin *joint = PhysicsJointPin::construct(mouse->getPhysicsBody(), body, location); joint->setMaxForce(5000.0f * body->getMass()); _scene->getPhysicsWorld()->addJoint(joint); _mouses.insert(std::make_pair(touch->getID(), mouse)); return true; } return false; }
bool PhysicsWorld::collisionBeginCallback(PhysicsContact& contact) { bool ret = true; PhysicsShape* shapeA = contact.getShapeA(); PhysicsShape* shapeB = contact.getShapeB(); PhysicsBody* bodyA = shapeA->getBody(); PhysicsBody* bodyB = shapeB->getBody(); std::vector<PhysicsJoint*> jointsA = bodyA->getJoints(); // check the joint is collision enable or not for (PhysicsJoint* joint : jointsA) { if (std::find(_joints.begin(), _joints.end(), joint) == _joints.end()) { continue; } if (!joint->isCollisionEnabled()) { PhysicsBody* body = joint->getBodyA() == bodyA ? joint->getBodyB() : joint->getBodyA(); if (body == bodyB) { contact.setNotificationEnable(false); return false; } } } // bitmask check if ((shapeA->getCategoryBitmask() & shapeB->getContactTestBitmask()) == 0 || (shapeA->getContactTestBitmask() & shapeB->getCategoryBitmask()) == 0) { contact.setNotificationEnable(false); } if (shapeA->getGroup() != 0 && shapeA->getGroup() == shapeB->getGroup()) { ret = shapeA->getGroup() > 0; } else { if ((shapeA->getCategoryBitmask() & shapeB->getCollisionBitmask()) == 0 || (shapeB->getCategoryBitmask() & shapeA->getCollisionBitmask()) == 0) { ret = false; } } if (contact.isNotificationEnabled()) { contact.setEventCode(PhysicsContact::EventCode::BEGIN); contact.setWorld(this); _eventDispatcher->dispatchEvent(&contact); } return ret ? contact.resetResult() : false; }
void HitMeScene::hitMeFire(Ref* sender) { Point velocity_delta = Point(CCRANDOM_0_1(), CCRANDOM_0_1()) * 300; velocity_delta = (CCRANDOM_0_1() < 0.5f)? velocity_delta : -velocity_delta; PhysicsBody* body = _hitItem->getPhysicsBody(); body->setVelocity(body->getVelocity() + velocity_delta); body->setAngularVelocity(body->getAngularVelocity() + 5.0f * CCRANDOM_0_1()); }
bool LandSprite::init() { if (!Sprite::init()) { return false; } Size visiableSize = Director::getInstance()->getVisibleSize(); Vec2 visiableOrigin = Director::getInstance()->getVisibleOrigin(); Sprite * landSprite1 = Sprite::create("assets/land.png"); landSprite1->setAnchorPoint(Vec2(0, 0)); landSprite1->setPosition(Vec2(visiableOrigin.x, visiableOrigin.y)); landSprite1->setScaleX(visiableSize.width / landSprite1->getContentSize().width / 2); Sprite * landSprite2 = Sprite::create("assets/land.png"); landSprite2->setAnchorPoint(Vec2(0, 0)); landSprite2->setPosition(Vec2(visiableOrigin.x + visiableSize.width / 2, visiableOrigin.y)); landSprite2->setScaleX(visiableSize.width / landSprite2->getContentSize().width / 2); Sprite * landSprite3 = Sprite::create("assets/land.png"); landSprite3->setAnchorPoint(Vec2(0, 0)); landSprite3->setPosition(Vec2(visiableOrigin.x + visiableSize.width, visiableOrigin.y)); landSprite3->setScaleX(visiableSize.width / landSprite3->getContentSize().width / 2); Sprite * landSprite4 = Sprite::create("assets/land.png"); landSprite4->setAnchorPoint(Vec2(0, 0)); landSprite4->setPosition(Vec2(visiableOrigin.x + visiableSize.width * 1.5, visiableOrigin.y)); landSprite4->setScaleX(visiableSize.width / landSprite4->getContentSize().width / 2); Node * landAnimNode = Node::create(); // node hold the land animation landAnimNode->addChild(landSprite1); landAnimNode->addChild(landSprite2); landAnimNode->addChild(landSprite3); landAnimNode->addChild(landSprite4); MoveBy * landForward = MoveBy::create(5, Vec2(-visiableSize.width, 0)); MoveBy * landBackward = MoveBy::create(0.001, Vec2(visiableSize.width, 0)); Sequence * moveSeq = Sequence::create(landForward, 0.001, landBackward,NULL); landSprite1->runAction(RepeatForever::create(moveSeq)); landSprite2->runAction(RepeatForever::create(moveSeq->clone())); landSprite3->runAction(RepeatForever::create(moveSeq->clone())); landSprite4->runAction(RepeatForever::create(moveSeq->clone())); this->addChild(landAnimNode); this->setAnchorPoint(Vec2(0, 0)); this->setContentSize(Size(visiableSize.width, landSprite1->getContentSize().height)); PhysicsBody * landPhysicsBody = PhysicsBody::createBox(Size(visiableSize.width, landSprite1->getContentSize().height), PhysicsMaterial(1, 1, 0)); landPhysicsBody->setGravityEnable(false); landPhysicsBody->setDynamic(false); landPhysicsBody->setContactTestBitmask(1); landPhysicsBody->setCollisionBitmask(2); this->setPhysicsBody(landPhysicsBody); return true; }
bool hitTest(PhysicsContact& contact, int mask) { PhysicsBody* a = contact.getShapeA()->getBody(); PhysicsBody* b = contact.getShapeB()->getBody(); int tagA = a->getTag(); int tagB = b->getTag(); int tag = tagA | tagB; return (tag & mask) == mask; }
void HelloWorld::setCollider (int tag){ Sprite* floor = (Sprite *)ScreenUtil::getChildbyTagRecursively(this, tag); auto size = Size(floor ->getContentSize().width * floor->getScaleX() , floor ->getContentSize().height * floor->getScaleY()); PhysicsBody* floorPb = PhysicsBody::createBox(size); floorPb->setDynamic(false); floor->setPhysicsBody(floorPb); }
void BoySprite::setPhysical() { // add the physical body PhysicsBody *body = PhysicsBody::create(); body->addShape(NORMAL_SHAPE); body->setDynamic(true); body->setLinearDamping(0.0f); body->setRotationEnable(false); this->setPhysicsBody(body); }
void Physics::removeStage(void) { int x = 1; while (gameBodies.size() > x) { PhysicsBody* obj = gameBodies.at(x); dynamicWorld->removeRigidBody(obj->getBody()); gameBodies.remove(obj); delete obj; graphics->removeObject(x); } }
void LevelThree::onContactSeperate(cocos2d::PhysicsContact &contact) { PhysicsBody* a = contact.getShapeA()->getBody(); PhysicsBody* b = contact.getShapeB()->getBody(); if (1 == a->getCollisionBitmask() || 1 == b->getCollisionBitmask()) { } }
bool HeroSprite::init() { bool bRet = false; do { CC_BREAK_IF(!Sprite::initWithSpriteFrameName("heroStand_0001.png")); Size heroSize = this->getContentSize(); PhysicsBody *body = PhysicsBody::createBox(heroSize-Size(0,16), PhysicsMaterial(0, 0, 0)); body->setLinearDamping(0.0f); body->setDynamic(true); body->setGravityEnable(true); body->setTag(TAG_HERO_PHYS_BODY); body->setCategoryBitmask(1<<2); body->setContactTestBitmask(1<<0 | 1<<1); body->setMass(50); body->setRotationEnable(false); this->setPhysicsBody(body); mState = STATE_IDLE; mRunAnimate = NULL; mSmokeRunAnimate = NULL; bRet = true; } while(0); return bRet; }
PhysicsBody* PhysicsBody::create() { PhysicsBody* body = new PhysicsBody(); if (body && body->init()) { body->autorelease(); return body; } CC_SAFE_DELETE(body); return nullptr; }
bool LevelThree::onContactPreSolve(cocos2d::PhysicsContact &contact, cocos2d::PhysicsContactPreSolve& solve) { PhysicsBody* a = contact.getShapeA()->getBody(); PhysicsBody* b = contact.getShapeB()->getBody(); if (1 == a->getCollisionBitmask() || 1 == b->getCollisionBitmask()) { solve.setRestitution(0); } return true; }
bool HelloWorld::onContactBegin(const PhysicsContact& contact) { PhysicsBody* a = contact.getShapeA()->getBody(); PhysicsBody* b = contact.getShapeB()->getBody(); this->removeChild(a->getNode()); this->removeChild(b->getNode()); return true; }
void PhysicsWorld::removeBody(int tag) { for (Object* obj : *_bodies) { PhysicsBody* body = dynamic_cast<PhysicsBody*>(obj); if (body->getTag() == tag) { removeBody(body); return; } } }
PhysicsBody::~PhysicsBody() { for (auto it = _joints.begin(); it != _joints.end(); ++it) { PhysicsJoint* joint = *it; PhysicsBody* other = joint->getBodyA() == this ? joint->getBodyB() : joint->getBodyA(); other->removeJoint(joint); delete joint; } CC_SAFE_DELETE(_info); }
PhysicsBody* PhysicsBody::createPolygon(const Vec2* points, int count, const PhysicsMaterial& material, const Vec2& offset) { PhysicsBody* body = new PhysicsBody(); if (body && body->init()) { body->addShape(PhysicsShapePolygon::create(points, count, material, offset)); body->autorelease(); return body; } CC_SAFE_DELETE(body); return nullptr; }
PhysicsBody* PhysicsBody::createBox(const Size& size, const PhysicsMaterial& material, const Vec2& offset) { PhysicsBody* body = new PhysicsBody(); if (body && body->init()) { body->addShape(PhysicsShapeBox::create(size, material, offset)); body->autorelease(); return body; } CC_SAFE_DELETE(body); return nullptr; }