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 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; }