bool HelloWorld::onTouchBegan(Touch* pTouch, Event* pEvent) { Size visibleSize = Director::getInstance()->getVisibleSize(); Point touchLocation = pTouch->getLocationInView(); touchLocation = Director::getInstance()->convertToGL(touchLocation); Sprite* projectileExmaple = Sprite::create("projectile-hd.png"); j+=1; auto OneBody = PhysicsBody::createBox(projectileExmaple->getContentSize()); OneBody->applyImpulse(Vect(100,500)); OneBody->setContactTestBitmask(0x04); projectileExmaple->setPhysicsBody(OneBody); projectileExmaple->setPosition(visibleSize.width/8,visibleSize.height/2); projectile.push_back(projectileExmaple); this->addChild(projectile.back(),j); Point offset = ccpSub(touchLocation, _player->getPosition()); float ratio = offset.y/offset.x; int targetX = _player->getContentSize().width/2 + visibleSize.width; int targetY = (targetX*ratio) + _player->getPosition().y; Vec2 targetPosition = Vec2(targetX,targetY); MoveTo* Move = MoveTo::create(2, targetPosition); projectile.back()->runAction(Move); return true; }
/** Resolve collision with an immovable object Computes & applies the collision impulse needed to keep the body from penetrating the given surface. */ bool Rigid::resolveCollision(const Point3F& p, const Point3F &normal) { atRest = false; Point3F v,r; getOriginVector(p,&r); getVelocity(r,&v); F32 n = -mDot(v,normal); if (n >= 0.0f) { // Collision impulse, straight forward force stuff. F32 d = getZeroImpulse(r,normal); F32 j = n * (1.0f + restitution) * d; Point3F impulse = normal * j; // Friction impulse, calculated as a function of the // amount of force it would take to stop the motion // perpendicular to the normal. Point3F uv = v + (normal * n); F32 ul = uv.len(); if (ul) { uv /= -ul; F32 u = ul * getZeroImpulse(r,uv); j *= friction; if (u > j) u = j; impulse += uv * u; } // applyImpulse(r,impulse); } return true; }
bool PxSingleActor::onAdd() { PROFILE_SCOPE(PxSingleActor_onAdd); // onNewDatablock for the server is called here // for the client it is called in unpackUpdate if ( !Parent::onAdd() ) return false; // JCFNOTE: we definitely have a datablock here because GameBase::onAdd checks that mNextPos = mLastPos = getPosition(); mNextRot = mLastRot = getTransform(); mResetPos = getTransform(); //Con::printf( "Set reset position to %g, %g, %g", mResetPos.getPosition().x, mResetPos.getPosition().y, mResetPos.getPosition().z ); if ( !mStartImpulse.isZero() ) applyImpulse( mStartImpulse ); PhysicsPlugin::getPhysicsResetSignal().notify( this, &PxSingleActor::onPhysicsReset, 1051.0f ); addToScene(); return true; }
void BreakoutMainScene::createBall() { // Create Ball cocos2d::log("Create Ball"); // Tao qua bong va thiet lap khung vat ly cho no ball = Sprite::create("breakout_img/breakout_ball.png"); ball->setAnchorPoint(Vec2::ANCHOR_MIDDLE); ball->setPosition(Vec2(WINSIZE.width/2 , WINSIZE.height/2 + 50)); auto ballBody = PhysicsBody::createCircle(ball->getContentSize().width/2 , PHYSICSBODY_MATERIAL_DEFAULT); ballBody->getShape(0)->setDensity(1.0f); // trong luc ballBody->getShape(0)->setFriction(0.0f); ballBody->getShape(0)->setRestitution(1.0f); ballBody->setDynamic(true); ballBody->setContactTestBitmask(0x00000001); ballBody->setGravityEnable(false); // Khong set gia toc // Tao 1 luc tac dong Vect force = Vect(900000.0f, -900000.0f); ballBody->applyImpulse(force); ball->setPhysicsBody(ballBody); ball->setTag(Tag::T_Ball); this->addChild(ball); }
void WindModificator::update (uint32_t deltaTime) { IEntity::update(deltaTime); b2Body *ownBody = getBodies()[0]; if (!_state) { ownBody->SetActive(false); return; } else { ownBody->SetActive(true); } for (b2ContactEdge* c = ownBody->GetContactList(); c != nullptr; c = c->next) { b2Contact *contact = c->contact; if (!contact->IsTouching()) continue; b2Body *bodyA = contact->GetFixtureA()->GetBody(); b2Body *bodyB = contact->GetFixtureB()->GetBody(); b2Body *body = ownBody != bodyA ? bodyA : bodyB; b2WorldManifold worldManifold; contact->GetWorldManifold(&worldManifold); const b2Manifold *manifold = contact->GetManifold(); for (int i = 0; i < manifold->pointCount; ++i) { const b2Vec2& contactPoint = worldManifold.points[i]; applyImpulse(body, contactPoint, _force); } } }
/** Resolve collision with another rigid body Computes & applies the collision impulses needed to keep the bodies from interpenetrating. tg: This function was commented out... I uncommented it, but haven't double checked the math. */ bool Rigid::resolveCollision(const Point3F& p, const Point3F &normal, Rigid* rigid) { atRest = false; Point3F v1,v2,r1,r2; getOriginVector(p,&r1); getVelocity(r1,&v1); rigid->getOriginVector(p,&r2); rigid->getVelocity(r2,&v2); // Make sure they are converging F32 nv = mDot(v1,normal); nv -= mDot(v2,normal); if (nv > 0.0f) return false; // Compute impulse F32 d, n = -nv * (1.0f + restitution * rigid->restitution); Point3F a1,b1,c1; mCross(r1,normal,&a1); invWorldInertia.mulV(a1,&b1); mCross(b1,r1,&c1); Point3F a2,b2,c2; mCross(r2,normal,&a2); rigid->invWorldInertia.mulV(a2,&b2); mCross(b2,r2,&c2); Point3F c3 = c1 + c2; d = oneOverMass + rigid->oneOverMass + mDot(c3,normal); Point3F impulse = normal * (n / d); applyImpulse(r1,impulse); impulse.neg(); applyImpulse(r2,impulse); return true; }
void shotRay() { int i; double forwardVector[3] = { -camOrientation[2], -camOrientation[5], -camOrientation[8] }; double shortest; int rayFound = 0; double currentRayLength; int bodyIndex = -1; for (i = 0; i < world.bodyCount; i++) { if (DYN_castRay( &world.bodies[i], camPosition, forwardVector, ¤tRayLength )) { if (rayFound) { if (currentRayLength < shortest) { shortest = currentRayLength; bodyIndex = i; } } else { rayFound = 1; shortest = currentRayLength; bodyIndex = i; } } } if (bodyIndex >= 0) { ALG_scale(forwardVector, 10); applyImpulse(&world, &world.bodies[bodyIndex], camPosition, forwardVector); } }
void Bomb::explode() { if (exploded == false) { exploded = true; b2Vec2 center = bodies[0].body_ptr->GetPosition(); float power = 300; float blast_radius = 15; //apply impulse to bodies size_t rays = 50; for (size_t i = 0; i < rays; i++) { float angle = (i / (float)rays) * 6.282; b2Vec2 rayDir( sinf(angle), cosf(angle) ); b2Vec2 rayEnd = center + blast_radius * rayDir; //check what this ray hits RayCastClosestCallback callback; world.RayCast(&callback, center, rayEnd); if ( callback.m_body ) { applyImpulse(callback.m_body, center, callback.m_point, power); } } } }
void DistanceConstraint::solve(const float dt) { // get some information that we need sf::Vector2f axis = getB()->getPosition() - getA()->getPosition(); float currentDistance = length(axis); sf::Vector2f unitAxis = axis * (1.f/currentDistance); // calculate relative velocity in the axis, we want to remove this float relVel = dot(getB()->getVelocity() - getA()->getVelocity(), unitAxis); float relDist = currentDistance-distance; // calculate impulse to solve float remove = relVel+relDist/dt; float impulse = remove / (getA()->getInverseMass() + getB()->getInverseMass()); // generate impulse vector sf::Vector2f I = unitAxis*impulse; // apply applyImpulse(I); }
void Player::step(float frame, float time) { this->time = time; applyImpulse(frame); run->apply(skeleton.get(), time, true); skeleton->getRootBone()->x = X_OFFSET; skeleton->getRootBone()->y = Y_OFFSET; skeleton->updateWorldTransform(); b2Vec2 speed = body->GetLinearVelocity(); sync(); if(speed.y > 1 && !isGrounded()) { setState(PlayerFalling); } else if(state == PlayerFalling && speed.y > -0.1){ setState(PlayerStanding); } else if(state == PlayerPreJump){ if(time > jumpStart + 0.05) doJump(); } else if(state == PlayerRunning && (impulse == ImpulseNone || impulse == ImpulseBoth) && speed.x < 0.1 && speed.x > -0.1){ setState(PlayerStanding); } }
void PhysicsBody::applyImpulse(const Vect& impulse) { applyImpulse(impulse, Vec2()); }
void PhysicsBody::applyImpulse(Point impulse) { applyImpulse(impulse, Point()); }
bool HelloWorld::init() { if ( !Layer::init() ) { return false; } this->isGameOver = false; visibleSize = Director::getInstance()->getVisibleSize(); // Ground setup groundSprite0 = Sprite::create("ground.png"); this->addChild(groundSprite0); groundSprite0->setPosition(Vec2(groundSprite0->getContentSize().width/2.0 , groundSprite0->getContentSize().height/2)); groundSprite1 = Sprite::create("ground.png"); this->addChild(groundSprite1); groundSprite1->setPosition(Vec2(visibleSize.width + groundSprite1->getContentSize().width/2.0 -10, groundSprite1->getContentSize().height/2)); auto groundbody0 = PhysicsBody::createBox(groundSprite0->getContentSize()); groundbody0->setDynamic(false); groundbody0->setContactTestBitmask(true); groundSprite0->setPhysicsBody(groundbody0); auto groundbody1 = PhysicsBody::createBox(groundSprite1->getContentSize()); groundbody1->setDynamic(false); groundbody1->setContactTestBitmask(true); groundSprite1->setPhysicsBody(groundbody1); // SkyGround setup Sprite *skySprite0 = Sprite::create("flappy_background.png"); Sprite *skySprite1 = Sprite::create("flappy_background.png"); Sprite *skySprite2 = Sprite::create("flappy_background.png"); this->addChild(skySprite0); this->addChild(skySprite1); this->addChild(skySprite2); skySprite0->setPosition(visibleSize.width/2, 168 + 200); skySprite1->setPosition(visibleSize.width/2 - skySprite1->getContentSize().width, 168 + 200); skySprite2->setPosition(visibleSize.width/2 + skySprite1->getContentSize().width, 168 + 200); // bird setup /* Sprite *birdSprite = Sprite::create("flappybird1.png"); this->addChild(birdSprite); birdSprite->setPosition(visibleSize.width/2, visibleSize.height/2 + 120); */ SpriteFrameCache* cache = SpriteFrameCache::getInstance(); cache->addSpriteFramesWithFile("bird.plist"); auto flyAnim = Animation::create(); for (int i = 1; i < 4; i++) { SpriteFrame * frame = cache->getSpriteFrameByName("flappybird" + to_string(i) + ".png"); flyAnim->addSpriteFrame(frame); } auto birdSprite = Sprite::createWithSpriteFrameName("flappybird1.png"); flyAnim->setDelayPerUnit(0.2f); auto action = Animate::create(flyAnim); auto animation = RepeatForever::create(action); birdSprite->runAction(animation); birdSprite->setPosition(Vec2(visibleSize.width/2, visibleSize.height/2 + 80)); this->addChild(birdSprite); auto birdBody = PhysicsBody::createCircle(17.0); birdBody->setDynamic(true); birdBody->setMass(1.0f); birdBody->setVelocity(Vec2(4.0f, 2.0f)); birdBody->setVelocityLimit(50); birdBody->setContactTestBitmask(true); birdSprite->setPhysicsBody(birdBody); //pipe setup topPipeSprite = Sprite::create("top_pipe.png"); bottomPipeSprite = Sprite::create("bottom_pipe.png"); topPipeSprite->setPosition(visibleSize.width + topPipeSprite->getContentSize().width/2, 600); auto pipebody0 = PhysicsBody::createBox(topPipeSprite->getContentSize()); pipebody0->setDynamic(false); topPipeSprite->setPhysicsBody(pipebody0); pipebody0->setContactTestBitmask(true); auto pipebody1 = PhysicsBody::createBox(bottomPipeSprite->getContentSize()); pipebody1->setDynamic(false); pipebody1->setContactTestBitmask(true); bottomPipeSprite->setPhysicsBody(pipebody1); this->positionBottomPipe(); this->addChild(topPipeSprite); this->addChild(bottomPipeSprite); //setup touch listener auto listener = EventListenerTouchOneByOne::create(); listener->setSwallowTouches(true); listener->onTouchBegan = [=](Touch *touch, Event *event){ if (!this->isGameOver) { birdBody->applyImpulse(Vec2(0, 90.0f)); } log("touch detected!"); return true; }; //setup collision listener auto plistener = EventListenerPhysicsContact::create(); plistener->onContactBegin = [=](PhysicsContact &contact){ log("collision detected!"); auto gameOverSprite = Sprite::create("game_over.png"); gameOverSprite->setPosition(Vec2(visibleSize.width/2, visibleSize.height/2)); this->addChild(gameOverSprite); this->isGameOver = true; auto restartListner = EventListenerTouchOneByOne::create(); restartListner->setSwallowTouches(true); restartListner->onTouchBegan = [](Touch *touch, Event* event){ Director::getInstance()->replaceScene(HelloWorld::createScene()); return true; }; Director::getInstance()->getEventDispatcher()->addEventListenerWithSceneGraphPriority(restartListner, gameOverSprite); return true; }; Director::getInstance()->getEventDispatcher()->addEventListenerWithSceneGraphPriority(listener, this); Director::getInstance()->getEventDispatcher()->addEventListenerWithSceneGraphPriority(plistener, this); this->scheduleUpdate(); return true; }
bool GameScene24::init() { if ( !Layer::init() ) { return false; } m_ui = UISimple::create(); this->addChild(m_ui, 30); Size visibleSize = Director::getInstance()->getWinSize(); Point origin = Director::getInstance()->getVisibleOrigin(); zidan = false; time = 5.0; //背景 auto bg = Sprite::create("level_24/bg.jpg"); bg->setPosition(Point(visibleSize.width* 0.5f,visibleSize.height * 0.5f)); this->addChild(bg); //创建月亮 moon = Sprite::create("level_24/hand1.png"); moon->setPosition(Point(visibleSize.width * 0.5f,visibleSize.height * 0.5f)); moon->setAnchorPoint(Point::ANCHOR_MIDDLE); moon->setTag(13); this->addChild(moon); auto body = PhysicsBody::createCircle(moon->getContentSize().width * 0.5f); body->getShape(0)->setFriction(0.0f); body->getShape(0)->setRestitution(1.001f); body->getShape(0)->setDensity(1.0f); body->setCategoryBitmask(1); // 0001 body->setCollisionBitmask(1); // 0001 body->setContactTestBitmask(1); // 0001 body->setGravityEnable(false); moon->setPhysicsBody(body); body->applyImpulse(Vect(3500000, 0)); //创建锯齿边缘 auto border = Sprite::create("level_24/border.png"); Size borderSize = border->getContentSize(); auto border1 = createBorder(Point(borderSize.width * 0.9f, borderSize.height * 0.7f)); this->addChild(border1); auto border2 = createBorder(Point(visibleSize.width - borderSize.width * 0.5f, borderSize.height * 0.7f)); border2->setFlippedX(true); this->addChild(border2); auto border3 = createBorder(Point(visibleSize.width * 0.5f, visibleSize.height * 0.15f)); borderSize = border3->getContentSize(); border3->setRotation(90.0f); this->addChild(border3); auto border4 = createBorder(Point(visibleSize.width * 0.5f, visibleSize.height * 0.8f)); borderSize = border4->getContentSize(); border4->setRotation(90.0f); this->addChild(border4); //子弹 shoot = Sprite::create("level_24/zidan1.png"); shoot->setPosition(Point( visibleSize.width * 0.5f,visibleSize.height * 0.15f+40)); shoot->setVisible(false); shoot->setAnchorPoint(Point::ANCHOR_MIDDLE); shoot->setTag(14); this->addChild(shoot); body1 = PhysicsBody::createCircle(shoot->getContentSize().width * 0.5f); body1->setCategoryBitmask(1); // 0001 body1->setCollisionBitmask(1); // 0001 body1->setContactTestBitmask(1); // 0001 shoot->setPhysicsBody(body1); //加载初始文字 boss = Sprite::create("new/text_she.png"); boss->setAnchorPoint(Point::ANCHOR_MIDDLE_BOTTOM); boss->setPosition(Point(visibleSize.width/2,visibleSize.height+100)); this->addChild(boss,30); auto pSequence2 = Sequence::create(CallFunc::create( [&]() { auto bossAct = MoveTo::create(0.5f, Point(Director::getInstance()->getVisibleSize().width/2, 680)); auto bossEase = EaseBackInOut::create(bossAct); boss->runAction(bossEase); }), DelayTime::create(1.0f), CallFunc::create( [&]() { boss->runAction(MoveTo::create(0.5f, Point(Director::getInstance()->getVisibleSize().width/2, Director::getInstance()->getVisibleSize().height+200))); }),NULL); this->runAction(pSequence2); //触摸监听 auto listener = EventListenerTouchOneByOne::create(); //listener->setSwallowTouches(true); listener->onTouchBegan = CC_CALLBACK_2(GameScene24::onTouchBegan,this); listener->onTouchEnded = CC_CALLBACK_2(GameScene24::onTouchEnded,this); _eventDispatcher->addEventListenerWithSceneGraphPriority(listener, this); //碰撞监听 auto contactListener = EventListenerPhysicsContact::create(); contactListener->onContactBegin = CC_CALLBACK_1(GameScene24::onContactBegin, this); _eventDispatcher->addEventListenerWithSceneGraphPriority(contactListener, this); //5秒内无动作失败 this->schedule(schedule_selector(GameScene24::update)); return true; }
int PhysicObject::methodsBridge(lua_State* luaVM) { if (isCurrentMethod("applyImpulse")) { applyImpulse(CVector(lua_tonumber(luaVM, 1), lua_tonumber(luaVM, 2), lua_tonumber(luaVM, 3)), CVector(lua_tonumber(luaVM, 4), lua_tonumber(luaVM, 5), lua_tonumber(luaVM, 6))); return 0; } if (isCurrentMethod("applyForce")) { applyForce(CVector(lua_tonumber(luaVM, 1), lua_tonumber(luaVM, 2), lua_tonumber(luaVM, 3)), CVector(lua_tonumber(luaVM, 4), lua_tonumber(luaVM, 5), lua_tonumber(luaVM, 6))); return 0; } if (isCurrentMethod("setLinearVelocity")) { setLinearVelocity(CVector(lua_tonumber(luaVM, 1), lua_tonumber(luaVM, 2), lua_tonumber(luaVM, 3))); return 0; } if (isCurrentMethod("getLinearVelocity")) { luaPushVector(luaVM, getLinearVelocity().x, getLinearVelocity().y, getLinearVelocity().z); return 1; } if (isCurrentMethod("setMass")) { setMass(lua_tonumber(luaVM, 1)); return 0; } if (isCurrentMethod("getMass")) { lua_pushnumber(luaVM, getMass()); return 1; } if (isCurrentMethod("setCollisionShapeType")) { setCollisionShapeType((CollisionShapeType)lua_tointeger(luaVM, 1)); return 0; } if (isCurrentMethod("getCollisionShapeType")) { lua_pushinteger(luaVM, getCollisionShapeType()); return 1; } if (isCurrentMethod("enablePhysics")) { enablePhysics(lua_toboolean(luaVM, 1)); return 0; } if (isCurrentMethod("isEnabledPhysics")) { lua_pushboolean(luaVM, isEnabledPhysics()); return 1; } if (isCurrentMethod("setAngularFactor")) { setAngularFactor(CVector(lua_tonumber(luaVM, 1), lua_tonumber(luaVM, 2), lua_tonumber(luaVM, 3))); return 0; } if (isCurrentMethod("getAngularFactor")) { luaPushVector(luaVM, getAngularFactor().x, getAngularFactor().y, getAngularFactor().z); return 1; } if (isCurrentMethod("setLinearFactor")) { setLinearFactor(CVector(lua_tonumber(luaVM, 1), lua_tonumber(luaVM, 2), lua_tonumber(luaVM, 3))); return 0; } if (isCurrentMethod("getLinearFactor")) { luaPushVector(luaVM, getLinearFactor().x, getLinearFactor().y, getLinearFactor().z); return 1; } if (isCurrentMethod("setTrigger")) { setTrigger(lua_toboolean(luaVM, 1)); return 0; } if (isCurrentMethod("isTrigger")) { lua_pushboolean(luaVM, isTrigger()); return 1; } if (isCurrentMethod("getCollisionShape")) { if (getCollisionShape() == NULL) { lua_pushnil(luaVM); } else { lua_getglobal(luaVM, getCollisionShape()->getGOID().c_str()); } return 1; } if (isCurrentMethod("setCollisionShape")) { if (lua_isnil(luaVM, 1)) { setCollisionShape(NULL); return 0; } lua_pushstring(luaVM, "cpointer"); lua_gettable(luaVM, -2); GOCollisionShape* o = (GOCollisionShape*)lua_tointeger(luaVM, -1); setCollisionShape(o); lua_pop(luaVM, -1); return 0; } if (isCurrentMethod("setEnableDeactivation")) { setEnableDeactivation(lua_toboolean(luaVM, 1)); return 0; } if (isCurrentMethod("isEnableDeactivation")) { lua_pushboolean(luaVM, isEnableDeactivation()); return 1; } if (isCurrentMethod("setFriction")) { setFriction(lua_tonumber(luaVM, 1)); return 0; } if (isCurrentMethod("getFriction")) { lua_pushnumber(luaVM, getFriction()); return 1; } if (isCurrentMethod("setRestitution")) { setRestitution(lua_tonumber(luaVM, 1)); return 0; } if (isCurrentMethod("getRestitution")) { lua_pushnumber(luaVM, getRestitution()); return 1; } if (isCurrentMethod("setLinearDumping")) { setLinearDumping(lua_tonumber(luaVM, 1)); return 0; } if (isCurrentMethod("getLinearDumping")) { lua_pushnumber(luaVM, getLinearDumping()); return 1; } if (isCurrentMethod("setAngularDumping")) { setAngularDumping(lua_tonumber(luaVM, 1)); return 0; } if (isCurrentMethod("getAngularDumping")) { lua_pushnumber(luaVM, getAngularDumping()); return 1; } if (isCurrentMethod("setAngularVelocity")) { setAngularVelocity(CVector(lua_tonumber(luaVM, 1), lua_tonumber(luaVM, 2), lua_tonumber(luaVM, 3))); return 0; } if (isCurrentMethod("getAngularVelocity")) { CVector av = getAngularVelocity(); luaPushVector(luaVM, av.x, av.y, av.z); return 1; } if (isCurrentMethod("addConstraint")) { if (lua_isnil(luaVM, 1)) { return 0; } lua_pushstring(luaVM, "cpointer"); lua_gettable(luaVM, -2); GOConstraint* o = (GOConstraint*)lua_tointeger(luaVM, -1); addConstraint(o); lua_pop(luaVM, -1); return 0; } if (isCurrentMethod("getConstraints")) { lua_newtable(luaVM); int tableIndex = lua_gettop(luaVM); vector<GOConstraint*> objs; for (unsigned int i = 0; i < constraints.size(); ++i) { if (constraints.at(i)->id == "undefined" || constraints.at(i)->id == "") continue; objs.push_back(constraints.at(i)); } for (unsigned int i = 0; i < objs.size(); ++i) { lua_pushinteger(luaVM, i+1); lua_getglobal(luaVM, objs.at(i)->id.c_str()); lua_settable (luaVM, tableIndex); } return 1; } if (isCurrentMethod("removeConstraint")) { if (lua_isnil(luaVM, 1)) { return 0; } lua_pushstring(luaVM, "cpointer"); lua_gettable(luaVM, -2); GOConstraint* o = (GOConstraint*)lua_tointeger(luaVM, -1); removeConstraint(o); lua_pop(luaVM, -1); return 0; } if (isCurrentMethod("removeAllConstrains")) { removeAllConstraints(); return 0; } if (isCurrentMethod("secondObjectForConstraint")) { if (lua_isnil(luaVM, 1)) { return 0; } lua_pushstring(luaVM, "cpointer"); lua_gettable(luaVM, -2); GOConstraint* o = (GOConstraint*)lua_tointeger(luaVM, -1); secondObjectForConstraint(o); lua_pop(luaVM, -1); return 0; } if (isCurrentMethod("isSecondObjectForConstraints")) { lua_newtable(luaVM); int tableIndex = lua_gettop(luaVM); vector<GOConstraint*> objs; for (unsigned int i = 0; i < secondObjectForConstraints.size(); ++i) { if (secondObjectForConstraints.at(i)->id == "undefined" || secondObjectForConstraints.at(i)->id == "") continue; objs.push_back(secondObjectForConstraints.at(i)); } for (unsigned int i = 0; i < objs.size(); ++i) { lua_pushinteger(luaVM, i+1); lua_getglobal(luaVM, objs.at(i)->id.c_str()); lua_settable (luaVM, tableIndex); } return 1; } if (isCurrentMethod("notUseAsSecondObjectForConstraint")) { if (lua_isnil(luaVM, 1)) { return 0; } lua_pushstring(luaVM, "cpointer"); lua_gettable(luaVM, -2); GOConstraint* o = (GOConstraint*)lua_tointeger(luaVM, -1); notUseAsSecondObjectForConstraint(o); lua_pop(luaVM, -1); return 0; } return LuaBridge::methodsBridge(luaVM); }
bool LevelThree::init() { if (!Layer::init()) { return false; } // 用于解决刚体穿透问题 this->scheduleUpdate(); // // 计时器 // this->schedule(schedule_selector(LevelThree::timeCounter), 1.0f); auto visibleSize = Director::getInstance()->getVisibleSize(); auto origin = Director::getInstance()->getVisibleOrigin(); // 加载背景贴图 auto spriteBg = Sprite::create("background.png"); spriteBg->setAnchorPoint(Vec2::ZERO); spriteBg->setPosition(Vec2::ZERO); addChild(spriteBg); // // 将资源加载到精灵帧缓存 // SpriteFrameCache::getInstance()->addSpriteFramesWithFile("threeColor.plist"); ballOne = Sprite::createWithSpriteFrameName("hero.png"); ballOne->setPosition(visibleSize.width / 2.0f, visibleSize.height / 2.0f); auto ballBodyOne = PhysicsBody::createCircle(ballOne->getContentSize().width/2, PHYSICSBODY_MATERIAL_DEFAULT); //是否设置物理为静态 //ballBodyOne->setDynamic(false); //设置物理的恢复力 ballBodyOne->getShape(0)->setRestitution(0.5f); //设置物体的摩擦力 ballBodyOne->getShape(0)->setFriction(0.0f); ballBodyOne->getShape(0)->setDensity(0.3f); // 设置质量 质量等于密度乘以面积 //ballBodyOne->getShape(0)->setMass(5000); // 设置物体是否受重力系数影响 ballBodyOne->setGravityEnable(true); ballBodyOne->setCategoryBitmask(1);// 分类掩码 ballBodyOne->setCollisionBitmask(1|2|4);// 碰撞掩码 ballBodyOne->setContactTestBitmask(2);// 接触测试掩码 // 设置物体的冲力 auto force = Vect(500000.0f, 500000.0f); ballBodyOne->applyImpulse(force); // 把物体添加到精灵 ballOne->setPhysicsBody(ballBodyOne); // 设置标志 ballOne->setTag(1); this->addChild(ballOne); //创建一个盒子,用来碰撞 auto edgeSpace = Sprite::create(); auto boundBody = PhysicsBody::createEdgeBox(visibleSize, PHYSICSBODY_MATERIAL_DEFAULT, 3); boundBody->getShape(0)->setFriction(0.0f); boundBody->getShape(0)->setRestitution(1.0f); edgeSpace->setPhysicsBody(boundBody); edgeSpace->setPosition(Vec2(visibleSize.width / 2, visibleSize.height / 2)); this->addChild(edgeSpace); edgeSpace->setTag(0); boundBody->setCategoryBitmask(4); boundBody->setCollisionBitmask(1 | 2 | 4); boundBody->setContactTestBitmask(0); // // 顶端吞吐动作,回调函数创建刚体 // auto spriteTest = Sprite::createWithSpriteFrameName("Cylinder.png"); // spriteTest->setPosition(Vec2(visibleSize.width / 2.0f, visibleSize.height)); // spriteTest->setAnchorPoint(Vec2::ANCHOR_MIDDLE_TOP); // this->addChild(spriteTest,100); // // 上下改变的seq // auto scaleby = ScaleBy::create(2, 2, 2); // auto scalebyback = scaleby->reverse(); // // auto funcall = CallFunc::create(this, callfunc_selector(startLayer::callbackC)); // auto seq = Sequence::create(scaleby, CallFuncN::create(CC_CALLBACK_1(LevelThree::callbackC, this)), scalebyback, nullptr); // // // 左右改变的seq // auto rightby = MoveBy::create(0.2f, Vec2(1, 0)); // auto rightbyback = rightby->reverse(); // auto leftby = MoveBy::create(0.2f, Vec2(-1, 0)); // auto leftbyback = leftby->reverse(); // auto seq1 = Sequence::create(rightby, rightbyback, leftby, leftbyback, nullptr); // // // 组合到一起 // auto spawn = Spawn::create(seq, seq1, nullptr); // // // 一直执行 或者 执行指定的次数也就是创建一定数量的刚体 // // auto repeat = Repeat::create(spawn,30); // 创建三十个刚体 // auto repeatForever = RepeatForever::create(spawn); // spriteTest->runAction(repeatForever); auto black1 = Sprite::createWithSpriteFrameName("white1.png"); int index = CCRANDOM_0_1() * 4; auto x = 0; auto y = 0; switch (index) { case 0: x = CCRANDOM_0_1() * 100; y = -CCRANDOM_0_1() * 100; break; case 1: x = -CCRANDOM_0_1() * 100; y = -CCRANDOM_0_1() * 100; break; case 2: x = -CCRANDOM_0_1() * 100; y = CCRANDOM_0_1() * 100; break; case 3: x = CCRANDOM_0_1() * 100; y = CCRANDOM_0_1() * 100; break; default: break; } black1->setPosition(visibleSize.width / 2.0f + x, visibleSize.height / 2.0f - y); auto blackBody1 = PhysicsBody::createBox(black1->getContentSize(), PHYSICSBODY_MATERIAL_DEFAULT); blackBody1->setDynamic(false); blackBody1->setCategoryBitmask(4); blackBody1->setCollisionBitmask(1 | 2 | 4); blackBody1->setContactTestBitmask(0); black1->setPhysicsBody(blackBody1); this->addChild(black1); auto rotation = RotateBy::create(2, 360); auto rotationback = rotation->reverse(); auto seq = Sequence::create(rotation, rotationback, nullptr); auto repeatRo = RepeatForever::create(seq); black1->runAction(repeatRo); auto yuantong0 = Sprite::createWithSpriteFrameName("yuantong.png"); yuantong0->setPosition(Vec2(visibleSize.width / 2.0f, visibleSize.height + yuantong0->getContentSize().height / 2.0f)); auto yuantongBody = PhysicsBody::createBox(yuantong0->getContentSize(), PHYSICSBODY_MATERIAL_DEFAULT); yuantongBody->setDynamic(false); yuantongBody->setCategoryBitmask(4); yuantongBody->setCollisionBitmask(1 | 2 | 4); yuantongBody->setContactTestBitmask(0); yuantong0->setPhysicsBody(yuantongBody); this->addChild(yuantong0); auto moveby0 = MoveBy::create(1.0f, Vec2(0, -90)); auto moveby0back = moveby0->reverse(); auto easein = EaseBackIn::create(moveby0); auto seq0 = Sequence::create(easein, CallFuncN::create(CC_CALLBACK_1(LevelThree::callbackC, this)), moveby0back, nullptr); auto repeat0 = RepeatForever::create(seq0); yuantong0->runAction(repeat0); listener = EventListenerTouchOneByOne::create(); listener->onTouchBegan = [=](Touch* touch, Event* event){ auto touchPosition = touch->getLocation(); Vec2 force = Vec2::ZERO; if (touchPosition.x > visibleSize.width/2.0f) { force = Vec2(50000.0f, 0.0f); } else { force = Vec2(-50000.0f, 0.0f); } ballOne->getPhysicsBody()->applyImpulse(force); return true; }; _eventDispatcher->addEventListenerWithSceneGraphPriority(listener, this); test = LabelAtlas::create(StringUtils::toString(LEVELTHREE), "1.png", 14, 21, '0'); test->setScale(2.0f); test->setAnchorPoint(Vec2::ANCHOR_MIDDLE); test->setPosition(Vec2(test->getContentSize().width, visibleSize.height - test->getContentSize().height)); this->addChild(test); test2 = LabelAtlas::create("0", "1.png", 14, 21, '0'); test2->setScale(2.0f); test2->setAnchorPoint(Vec2::ANCHOR_MIDDLE); test2->setPosition(Vec2(visibleSize.width - test2->getContentSize().width, visibleSize.height - test2->getContentSize().height)); this->addChild(test2); return true; }
void cpSpaceStep(cpSpace *space, cpFloat dt) { // don't step if the timestep is 0! if(dt == 0.0f) return; space->stamp++; cpFloat prev_dt = space->curr_dt; space->curr_dt = dt; cpArray *bodies = space->bodies; cpArray *constraints = space->constraints; cpArray *arbiters = space->arbiters; // Reset and empty the arbiter list. for(int i=0; i<arbiters->num; i++){ cpArbiter *arb = (cpArbiter *)arbiters->arr[i]; arb->state = cpArbiterStateNormal; // If both bodies are awake, unthread the arbiter from the contact graph. if(!cpBodyIsSleeping(arb->body_a) && !cpBodyIsSleeping(arb->body_b)){ cpArbiterUnthread(arb); } } arbiters->num = 0; cpSpaceLock(space); { // Integrate positions for(int i=0; i<bodies->num; i++){ cpBody *body = (cpBody *)bodies->arr[i]; body->position_func(body, dt); } // Find colliding pairs. cpSpacePushFreshContactBuffer(space); cpSpatialIndexEach(space->activeShapes, (cpSpatialIndexIteratorFunc)cpShapeUpdateFunc, NULL); cpSpatialIndexReindexQuery(space->activeShapes, (cpSpatialIndexQueryFunc)cpSpaceCollideShapes, space); } cpSpaceUnlock(space, cpFalse); // If body sleeping is enabled, do that now. if(space->sleepTimeThreshold != INFINITY || space->enableContactGraph){ cpSpaceProcessComponents(space, dt); } cpSpaceLock(space); { // Clear out old cached arbiters and call separate callbacks cpHashSetFilter(space->cachedArbiters, (cpHashSetFilterFunc)cpSpaceArbiterSetFilter, space); // Prestep the arbiters and constraints. cpFloat slop = space->collisionSlop; cpFloat biasCoef = 1.0f - cpfpow(space->collisionBias, dt); for(int i=0; i<arbiters->num; i++){ cpArbiterPreStep((cpArbiter *)arbiters->arr[i], dt, slop, biasCoef); } for(int i=0; i<constraints->num; i++){ cpConstraint *constraint = (cpConstraint *)constraints->arr[i]; cpConstraintPreSolveFunc preSolve = constraint->preSolve; if(preSolve) preSolve(constraint, space); constraint->klass->preStep(constraint, dt); } // Integrate velocities. cpFloat damping = cpfpow(space->damping, dt); cpVect gravity = space->gravity; for(int i=0; i<bodies->num; i++){ cpBody *body = (cpBody *)bodies->arr[i]; body->velocity_func(body, gravity, damping, dt); } // Apply cached impulses cpFloat dt_coef = (prev_dt == 0.0f ? 0.0f : dt/prev_dt); for(int i=0; i<arbiters->num; i++){ cpArbiterApplyCachedImpulse((cpArbiter *)arbiters->arr[i], dt_coef); } for(int i=0; i<constraints->num; i++){ cpConstraint *constraint = (cpConstraint *)constraints->arr[i]; constraint->klass->applyCachedImpulse(constraint, dt_coef); } // Run the impulse solver. cpSpaceArbiterApplyImpulseFunc applyImpulse = space->arbiterApplyImpulse; for(int i=0; i<space->iterations; i++){ for(int j=0; j<arbiters->num; j++){ applyImpulse((cpArbiter *)arbiters->arr[j]); } for(int j=0; j<constraints->num; j++){ cpConstraint *constraint = (cpConstraint *)constraints->arr[j]; constraint->klass->applyImpulse(constraint); } } // Run the constraint post-solve callbacks for(int i=0; i<constraints->num; i++){ cpConstraint *constraint = (cpConstraint *)constraints->arr[i]; cpConstraintPostSolveFunc postSolve = constraint->postSolve; if(postSolve) postSolve(constraint, space); } // run the post-solve callbacks for(int i=0; i<arbiters->num; i++){ cpArbiter *arb = (cpArbiter *) arbiters->arr[i]; cpCollisionHandler *handler = arb->handler; handler->postSolve(arb, space, handler->data); } } cpSpaceUnlock(space, cpTrue); }
bool HelloWorld::init() { if (!Layer::init()) { return false; } Size visibleSize = Director::getInstance()->getVisibleSize(); Vec2 origin = Director::getInstance()->getVisibleOrigin(); auto edgeBody = PhysicsBody::createEdgeBox(visibleSize, PhysicsMaterial(0,1,0), 3); edgeBody->setDynamic(false); auto edgeNode = Node::create(); edgeNode->setPosition(Point(visibleSize.width / 2 + origin.x, visibleSize.height / 2 + origin.y)); edgeNode->setPhysicsBody(edgeBody); this->addChild(edgeNode); bg = Sprite::create("background.png"); ball = Sprite::create("ball.png"); paddle = Sprite::create("paddle.png"); label = Label::createWithSystemFont(std::to_string(score), "Arial", 40); bg->setAnchorPoint(Vec2(0.5, 0.5)); ball->setAnchorPoint(Vec2(0, 1)); paddle->setAnchorPoint(Vec2(0, 1)); label->setAnchorPoint(Vec2(0, 0)); bg->setPosition(320, 240); ball->setPosition(160, 240); paddle->setPosition(208, 48); for (int i = 0; i < 8; i++) { for (int j = 0; j < 5; j++) { block[i][j] = Sprite::create("brick.png"); block[i][j]->setAnchorPoint(Vec2(0, 1)); block[i][j]->setPosition(192 + 32 * i, 400 - 16 * j); } } auto spriteBody = PhysicsBody::createCircle(ball->getContentSize().width/2, PhysicsMaterial(0, 1, 0)); spriteBody->setCollisionBitmask(1); spriteBody->setContactTestBitmask(true); Vect force = Vect(80, -80); spriteBody->applyImpulse(force); ball->setPhysicsBody(spriteBody); auto spriteBody2 = PhysicsBody::createBox(paddle->getContentSize(), PhysicsMaterial(0, 1, 0)); spriteBody2->setDynamic(false); paddle->setPhysicsBody(spriteBody2); for (int i = 0; i < 8; i++) { for (int j = 0; j < 5; j++) { auto blockBody = PhysicsBody::createBox(block[i][j]->getContentSize(), PhysicsMaterial(0, 1, 0)); blockBody->setCollisionBitmask(2); blockBody->setContactTestBitmask(true); blockBody->setDynamic(false); block[i][j]->setPhysicsBody(blockBody); } } this->addChild(bg, 0); this->addChild(ball, 0); this->addChild(paddle, 0); this->addChild(label, 1); for (int i = 0; i < 8; i++) { for (int j = 0; j < 5; j++) { this->addChild(block[i][j], 0); } } this->scheduleUpdate(); auto eventListener = EventListenerKeyboard::create(); auto contactListener = EventListenerPhysicsContact::create(); eventListener->onKeyPressed = [=](EventKeyboard::KeyCode keyCode, Event* event)->void { Vector<FiniteTimeAction*> actions; Vec2 loc = event->getCurrentTarget()->getPosition(); switch (keyCode) { case EventKeyboard::KeyCode::KEY_LEFT_ARROW: case EventKeyboard::KeyCode::KEY_A: paddle->setPosition(paddle->getPosition().x - 16, paddle->getPosition().y); if (paddle->getPosition().x < 0) { paddle->setPosition(560, paddle->getPosition().y); } break; case EventKeyboard::KeyCode::KEY_RIGHT_ARROW: case EventKeyboard::KeyCode::KEY_D: paddle->setPosition(paddle->getPosition().x + 16, paddle->getPosition().y); if (paddle->getPosition().x > 560) { paddle->setPosition(0, paddle->getPosition().y); } break; } }; contactListener->onContactBegin = CC_CALLBACK_1(HelloWorld::onContactBegin, this); this->_eventDispatcher->addEventListenerWithSceneGraphPriority(eventListener, paddle); this->getEventDispatcher()->addEventListenerWithSceneGraphPriority(contactListener, this); return true; }
bool Game1::init() { if (!Layer::init()) { return false; } padding = 70; counts = 25; flag = 0; //The Size seting. auto visibleSize = Director::getInstance()->getVisibleSize(); auto origin = Director::getInstance()->getVisibleOrigin(); //Keyboard seting. this->setKeyboardEnabled(true); this->setKeypadEnabled(true); //create the background auto BackgroundSprite = Sprite::create("Game/Level_1/background.png"); BackgroundSprite->setPosition(Vec2(visibleSize.width / 2, visibleSize.height / 2)); addChild(BackgroundSprite); //create the bound. edgeSp = Sprite::create(); auto boundBody = PhysicsBody::createEdgeBox(visibleSize, PhysicsMaterial(1.0f, 1.0f, 0.0f), 3); edgeSp->setPosition(Point(visibleSize.width / 2, visibleSize.height / 2)); edgeSp->setTag(0); edgeSp->setPhysicsBody(boundBody); this->addChild(edgeSp); //create the ball ba = Ball::create(); ba->bindSprite(Sprite::create("Game/Level_1/ball.png")); this->addChild(ba); ball = ba->getSprite(); ball->setPosition(100, 100); auto ballBody = PhysicsBody::createCircle(ball->getContentSize().width / 2, PhysicsMaterial(1.0f, 1.0f, 0.0f)); ballBody->setGravityEnable(false); Vect force = Vect(40000.0f, 40000.0f); ballBody->applyImpulse(force); ballBody->setCategoryBitmask(0x0001); ballBody->setCollisionBitmask(0x0001); ballBody->setContactTestBitmask(0x0001); ball->setPhysicsBody(ballBody); ball->setTag(1); //create the paddle. pa = Paddle::create(); pa->bindSprite(Sprite::create("Game/Level_1/paddle.png")); paddle = pa->getSprite(); this->addChild(pa); auto paddleBody = PhysicsBody::createBox(paddle->getContentSize(), PhysicsMaterial(10.0f, 1.0f, 0.0f)); paddleBody->setGravityEnable(false); paddleBody->setDynamic(false); paddle->setPhysicsBody(paddleBody); paddle->setTag(2); paddle->setPosition(visibleSize.width / 2, visibleSize.height * 0.05); //add the pink block. Sprite* block; bl = Block::create(); bl->bindSprite(Sprite::create("block/block4.png")); this->addChild(bl); block = bl->getSprite(); auto blockBody = PhysicsBody::createBox(block->getContentSize(), PhysicsMaterial(10.0f, 1.0f, 0.0f)); blockBody->setDynamic(false); blockBody->setCategoryBitmask(0x0001); blockBody->setCollisionBitmask(0x0001); blockBody->setContactTestBitmask(0x0001); block->setPhysicsBody(blockBody); block->setTag(10); for (int j = 0; j < 5; j++) { int Xoffset = 120; for (int i = 0; i < 5; i++) { Xoffset = padding + Xoffset; if (j == 4 && i == 4) { block->setPosition(Vec2(Xoffset, visibleSize.height*0.8 - j * 70)); } else { addBlock(Vec2(Xoffset, visibleSize.height*0.8 - j * 70)); } } } this->schedule(schedule_selector(Game1::callback4)); //add the pause btn. auto item1 = MenuItemImage::create("Game/btn_pause.png", "Game/btn_pause.png",CC_CALLBACK_1(Game1::call, this)); auto menu = Menu::create(item1, NULL); menu->setPosition(Vec2(visibleSize.width * 0.9, visibleSize.height * 0.95)); addChild(menu, 1); //eventlistener auto contactListener = EventListenerPhysicsContact::create(); contactListener->onContactBegin = CC_CALLBACK_1(Game1::onContactBegin, this); _eventDispatcher->addEventListenerWithSceneGraphPriority(contactListener, this); return true; }
CollisionResult resolveCollision ( DYN_Context *context, DYN_Body *a, DYN_Body *b, double *collisionPoint, double *impulseDirection ) { double radiusA[3]; double radiusB[3]; double collisionPointVelocityA[3]; double collisionPointVelocityB[3]; double normal[3]; // The impulse's direction A gives B. double tmp[3]; double relativeCollisionPointVelocity[3]; double impulseStrength; double elasticity = 1; double normalComponent; double tangentialComponent; const double CRITICAL_SLOW_SPEED = 0.001; char isSeparatingSlowly; // Get a normalized unit vector memcpy(normal, impulseDirection, sizeof(normal)); ALG_normalizeVector(normal); // Get vectors drawn from mass center to the collision point. ALG_getPointToPointVector(radiusA, a->position, collisionPoint); ALG_getPointToPointVector(radiusB, b->position, collisionPoint); // Calculate the speed of the collision points on the bodies. memcpy(collisionPointVelocityA, a->velocity, sizeof(collisionPointVelocityA)); ALG_crossProduct(tmp, a->angularVelocity, radiusA); ALG_translate(collisionPointVelocityA, tmp); memcpy(collisionPointVelocityB, b->velocity, sizeof(collisionPointVelocityB)); ALG_crossProduct(tmp, b->angularVelocity, radiusB); ALG_translate(collisionPointVelocityB, tmp); // Get relative collision point velocity ALG_getPointToPointVector( relativeCollisionPointVelocity, collisionPointVelocityA, collisionPointVelocityB ); normalComponent = ALG_dotProduct(normal, relativeCollisionPointVelocity); tangentialComponent = sqrt( ALG_getVectorLength(relativeCollisionPointVelocity) - normalComponent*normalComponent ); isSeparatingSlowly = (normalComponent * -elasticity) < CRITICAL_SLOW_SPEED; if (isSeparatingSlowly) { fprintf(DYN_log, "The two bodies are separating slowly! (elasticity: %g)\n", elasticity); } fprintf(DYN_log, "Normal component of relative speed: %g\n", normalComponent); fprintf( DYN_log, "Tangential component of relative speed: %g\n", tangentialComponent ); if (normalComponent > 0) { // In this case, the two bodies separating, they cannot collide. return DYN_SEPARATING; } // Calculate the strength of the impulse { double tmp[3]; double tmp2[3]; double tmpVectorA[3]; double tmpVectorB[3]; ALG_crossProduct(tmp, radiusA, normal); ALG_transform(tmp2, tmp, a->staticAttributes->inverseInertiaTensor); ALG_crossProduct(tmpVectorA, tmp2, radiusA); ALG_crossProduct(tmp, radiusB, normal); ALG_transform(tmp2, tmp, b->staticAttributes->inverseInertiaTensor); ALG_crossProduct(tmpVectorB, tmp2, radiusB); impulseStrength = (-(1 + elasticity)*ALG_dotProduct(relativeCollisionPointVelocity, normal) )/ (1/a->staticAttributes->mass + 1/b->staticAttributes->mass + ALG_dotProduct(tmpVectorA, normal) + ALG_dotProduct(tmpVectorB, normal) ) ; } ALG_scale(normal, impulseStrength); applyImpulse(context, b, collisionPoint, normal); ALG_scale(normal, -1); applyImpulse(context, a, collisionPoint, normal); if (isSeparatingSlowly) { return DYN_STICKEDTOGETHER; } else { return DYN_COLLIDED; } }
bool Game1::onContactBegin(const PhysicsContact& contact) { Sprite* spriteA = (Sprite*)contact.getShapeA()->getBody()->getNode(); Sprite* spriteB = (Sprite*)contact.getShapeB()->getBody()->getNode(); int tagA = spriteA->getTag(); int tagB = spriteB->getTag(); if (tagA >= 3) { spriteA->removeFromParentAndCleanup(true); counts--; if (tagA == 3) { paddle->setScale(1.35f); } if (tagA == 4) { paddle->setScale(0.8f); } if (tagA == 5) { paddle->setScale(1.2f); } if (tagA == 10) { flag = 1; ba2 = Ball::create(); ba2->bindSprite(Sprite::create("Game/Level_1/ball.png")); this->addChild(ba2); ball2 = ba2->getSprite(); ball2->setPosition(100, 100); auto ballBody = PhysicsBody::createCircle(ball->getContentSize().width / 2.); ballBody->getShape(0)->setRestitution(1.0f); ballBody->getShape(0)->setFriction(0.0f); ballBody->getShape(0)->setDensity(1.0f); ballBody->setGravityEnable(false); Vect force = Vect(40000.0f, 40000.0f); ballBody->applyImpulse(force); ballBody->setCategoryBitmask(0x0001); ballBody->setCollisionBitmask(0x0001); ballBody->setContactTestBitmask(0x0001); ball2->setPhysicsBody(ballBody); ball2->setTag(1); ball2->setScale(1.1f); } } if (tagB >= 3) { spriteB->removeFromParentAndCleanup(true); counts--; if (tagB == 3) { paddle->setScale(1.35f); } if (tagB == 4) { paddle->setScale(0.8f); } if (tagB == 5) { paddle->setScale(1.2f); } if (tagB == 10) { flag = 1; ba2 = Ball::create(); ba2->bindSprite(Sprite::create("Game/Level_1/ball.png")); this->addChild(ba2); ball2 = ba2->getSprite(); ball2->setPosition(100, 100); auto ballBody = PhysicsBody::createCircle(ball->getContentSize().width / 2.); ballBody->getShape(0)->setRestitution(1.0f); ballBody->getShape(0)->setFriction(0.0f); ballBody->getShape(0)->setDensity(1.0f); ballBody->setGravityEnable(false); Vect force = Vect(40000.0f, 40000.0f); ballBody->applyImpulse(force); ballBody->setCategoryBitmask(0x0001); ballBody->setCollisionBitmask(0x0001); ballBody->setContactTestBitmask(0x0001); ball2->setPhysicsBody(ballBody); ball2->setTag(1); ball2->setScale(1.1f); } } return true; }
void PowerUp::SetPowerUp(cocos2d::Layer *layer, float posX, float posY) { int i = cocos2d::RandomHelper::random_int(0, 20); //set this to everytime for testing purposes //CCLOG("I: %i", i); this->x = posX; this->y = posY; if (i == 1 || i == 2) //life Up { auto LifeUp = Sprite::create("Extra Life.png"); // May not need the auto auto LifeUpBounding = PhysicsBody::createCircle((10.0f, 10.0f), PhysicsMaterial(1.0f, 2.0f, 0.0f)); a = cocos2d::RandomHelper::random_int(-12000, 12000); b = cocos2d::RandomHelper::random_int(8000, 10000); //powerUpBounding->setVelocity(Vec2(a, b)); // LifeUpBounding->applyImpulse(Vec2(a, b)); LifeUpBounding->applyTorque(12000); LifeUpBounding->applyForce(Vect(a, b)); LifeUpBounding->setDynamic(true); LifeUpBounding->setGravityEnable(true); LifeUpBounding->setContactTestBitmask(true); LifeUpBounding->setCategoryBitmask(1); LifeUpBounding->setCollisionBitmask(LiveUp_Bitmask); LifeUp->setPhysicsBody(LifeUpBounding); LifeUp->setPosition(Vec2(x, y)); layer->addChild(LifeUp); LifeUp->setZOrder(1); } else if (i == 3 || i == 4 || i == 5 || i == 6)// Ball Split { auto two = Sprite::create("MultiBall Two.png"); // May not need the auto auto twoBounding = PhysicsBody::createCircle((10.0f, 10.0f), PhysicsMaterial(1.0f, 2.0f, 0.0f)); a = cocos2d::RandomHelper::random_int(-12000, 12000); b = cocos2d::RandomHelper::random_int(8000, 10000); //powerUpBounding->setVelocity(Vec2(a, b)); // twoBounding->applyImpulse(Vec2(a, b)); twoBounding->applyTorque(12000); twoBounding->applyForce(Vect(a, b)); twoBounding->setDynamic(true); twoBounding->setGravityEnable(true); twoBounding->setContactTestBitmask(true); twoBounding->setCategoryBitmask(1); twoBounding->setCollisionBitmask(TwoSplit_Bitmask); two->setPhysicsBody(twoBounding); two->setPosition(Vec2(x, y)); layer->addChild(two); two->setZOrder(1); } else if (i == 7 || i == 8 || i == 9)// Three Way (Imagine the chance to disappoint two women at once.) { auto three= Sprite::create("MultiBall Three.png"); // May not need the auto auto threeBounding = PhysicsBody::createCircle((10.0f, 10.0f), PhysicsMaterial(1.0f, 2.0f, 0.0f)); a = cocos2d::RandomHelper::random_int(-12000, 12000); b = cocos2d::RandomHelper::random_int(8000, 10000); //powerUpBounding->setVelocity(Vec2(a, b)); // threeBounding->applyImpulse(Vec2(a, b)); threeBounding->applyTorque(12000); threeBounding->applyForce(Vect(a, b)); threeBounding->setDynamic(true); threeBounding->setGravityEnable(true); threeBounding->setContactTestBitmask(true); threeBounding->setCategoryBitmask(1); threeBounding->setCollisionBitmask(ThreeSplit_Bitmask); three->setPhysicsBody(threeBounding); three->setPosition(Vec2(x, y)); layer->addChild(three); three->setZOrder(1); } else if (i == 10)// Nine Way! { auto nine = Sprite::create("MultiBall Nine.png"); // May not need the auto auto nineBounding = PhysicsBody::createCircle((10.0f, 10.0f), PhysicsMaterial(1.0f, 2.0f, 0.0f)); a = cocos2d::RandomHelper::random_int(-12000, 12000); b = cocos2d::RandomHelper::random_int(8000, 10000); //powerUpBounding->setVelocity(Vec2(a, b)); // nineBounding->applyImpulse(Vec2(a, b)); nineBounding->applyTorque(12000); nineBounding->applyForce(Vect(a, b)); nineBounding->setDynamic(true); nineBounding->setGravityEnable(true); nineBounding->setContactTestBitmask(true); nineBounding->setCategoryBitmask(1); nineBounding->setCollisionBitmask(NineSplit_Bitmask); nine->setPhysicsBody(nineBounding); //sets a bounding box around brick. nine->setPosition(Vec2(x, y)); layer->addChild(nine); nine->setZOrder(1); } }