void HelloWorld::addBox(cocos2d::Vec2 position){
    
    // 0b010 | 0b001 = 0b011
    
    auto r = Sprite::create();
    r->setTextureRect(Rect(0, 0, 50, 50));
    r->setPhysicsBody(PhysicsBody::createBox(r->getContentSize()));
    addChild(r);
    r->setPosition(position);
    
    switch (rand()%3) {
        case 0:
            r->setColor(Color3B(255, 0, 0));
            r->getPhysicsBody()->setContactTestBitmask(RED_BIT_MASK);
            break;
        case 1:
            r->setColor(Color3B(0, 255, 0));
            r->getPhysicsBody()->setContactTestBitmask(GREEN_BIT_MASK);
            break;
        case 2:
            r->setColor(Color3B(0, 0, 255));
            r->getPhysicsBody()->setContactTestBitmask(BLUE_BIT_MASK);
            break;
        default:
            break;
    }
}
Beispiel #2
0
//第一关(添加5关的关卡刚体)
void GameLayer:: addGangti1(){
    
    //木头
    for (int i = 1; i<=9 ;i++ ) {
        auto str = __String::createWithFormat("wood_%d",i);
        Sprite* woods1 = node->getChildByName<Sprite*>(str->getCString());
//       log("tag = %d",woods1->getTag());
        if (woods1->getTag() ==5) {
            auto body = PhysicsBody::createBox(woods1->getContentSize());
        body->setDynamic(false);
            body->getShape(0)->setRestitution(1);//反弹力
         body->getShape(0)->setFriction(0);//摩擦力
            woods1->setPhysicsBody(body);
            woods1->getPhysicsBody()->setContactTestBitmask(WALL_MASK);
        }

        
    }

    //墙壁
    for (int i =1; i<=4; i++) {
        auto str2 =__String::createWithFormat("wall_%d",i);
        auto wall = node->getChildByName<Sprite*>(str2->getCString());
        if (wall->getTag() == 25) {
            auto body2 = PhysicsBody::createBox(Size(wall->getContentSize().width,wall->getContentSize().height));//den res fri
            
            body2->setDynamic(false);
            body2->getShape(0)->setFriction(0);
            body2->getShape(0)->setRestitution(1);

            
            wall->setPhysicsBody(body2);
            
            wall->getPhysicsBody()->setContactTestBitmask(WALL_MASK);
        }
        
    }
    
    //石头
    for (int i =1; i<= 2; i++) {

        auto str3 =__String::createWithFormat("stone_%d",i);
        auto stone = node->getChildByName<Sprite*>(str3->getCString());
        if (stone->getTag() == 45) {
//            auto body2 = PhysicsBody::createBox(Size(stone->getContentSize().width,stone->getContentSize().height));//den res fri
//
            auto body3 = PhysicsBody::createCircle(stone->getContentSize().width/2);
            
            body3->setDynamic(false);
            body3->getShape(0)->setFriction(0);
            body3->getShape(0)->setRestitution(1.5);//弹力
            stone->setPhysicsBody(body3);
            stone->getPhysicsBody()->setContactTestBitmask(WALL_MASK);
        }
    }
    
    
}
Beispiel #3
0
bool HeroSprite::onContactBegin(PhysicsContact& contact) {

	if (mState == STATE_DEAD) {
		return false;
	}

    if (hitTest(contact, TAG_HERO_PHYS_BODY|TAG_GROUND1_PHYS_BODY)) {

		Vec2 v = getPhysicsBody()->getVelocity();
		getPhysicsBody()->setVelocity(Vec2(0, 0));
		getPhysicsBody()->resetForces();
		getPhysicsBody()->setContactTestBitmask(1<<1);

        if ((mState == STATE_JUMP1)
                || (mState == STATE_JUMP2)
                || (mState == STATE_IDLE)) {

			if (v.y < -200)
				stand();
			else
				mState = STATE_STAND;

			CallFunc *callback = CallFunc::create([&]() {
				run();
			});
			auto delay = DelayTime::create(0.05f);
			auto seq = Sequence::create(delay, callback, nullptr);
			runAction(seq);
        }
    }

    if (hitTest(contact, TAG_HERO_PHYS_BODY|TAG_BARRIER_PHYS_BODY)) {
		BackgroundLayer * bg = (BackgroundLayer *)(getScene()
				->getChildByName("gamelayer")
				->getChildByName("background"));
		bg->stopMove();

		auto scale1 = ScaleTo::create(0.1, 0.9, 0.9);
		auto scale2 = ScaleTo::create(0.1, 1.0, 1.0);
		auto seq1 = Sequence::create(scale1, scale2, nullptr);
		getNodeByTag(contact, TAG_BARRIER_PHYS_BODY)->runAction(seq1);

		getPhysicsBody()->setContactTestBitmask(1<<1 | 1<<0);
		dead();

		CallFunc *callback = CallFunc::create([]() {
			Director::getInstance()->replaceScene(GameOverScene::create());
		});
		auto seq = Sequence::create(DelayTime::create(1), callback, nullptr);
		runAction(seq);

		EventCustom event("EVENT_GameOver");
		_eventDispatcher->dispatchEvent(&event);
    }

	return true;
}
Beispiel #4
0
void SplitBomb::fadeout(){
    stopAnim();
    getPhysicsBody()->setEnable(false);
    const std::function<void()> callback = [&](void){
        m_armature->setOpacity(255);
        getPhysicsBody()->setEnable(true);
        this->hide();
    };
    m_armature->runAction( CCSequence::create(CCFadeOut::create(0.3f),CallFunc::create(callback), NULL) );
}
Beispiel #5
0
void Unit::SetDef(const UnitInfo& info)
{
    Object::SetDef(info.m_DefInfo);
    getPhysicsBody()->getFirstShape()->setMaterial(PhysicsMaterial(0, 0, 0));
    getPhysicsBody()->setCategoryBitmask(OBJ_UNIT);
    getPhysicsBody()->setCollisionBitmask(OBJ_ALL - OBJ_UNIT - OBJ_DEF - OBJ_LASER);
    getPhysicsBody()->setContactTestBitmask(OBJ_LASER + OBJ_MISSILE + OBJ_DEF);
    getPhysicsBody()->setVelocityLimit(m_DefInfo.m_MoveSpeed * 1.5f);
    SetHpBar("Image/Interface/hp_bar_small.png");
    m_UnitInfo = info;
}
Beispiel #6
0
/*
创建一个Node
*/
cocos2d::Node * MyAction::createNode(int tag, cocos2d::PhysicsBody * physics_body, bool dynamic)
{
	auto node = Node::create();
	node->setTag(tag);
	if (physics_body != NULL) {
		node->setPhysicsBody(physics_body);
		node->getPhysicsBody()->setContactTestBitmask(MAX_UINT);
		node->getPhysicsBody()->setDynamic(dynamic);
	}
	return node;
}
Beispiel #7
0
/*
创建一个Sprite(不可设置AnchorPoint)
*/
cocos2d::Sprite * MyAction::createSprite(std::string file_name, int tag, Vec2 position, cocos2d::PhysicsBody * physics_body, bool dynamic)
{
	auto sprite = Sprite::create(file_name);
	sprite->setTag(tag);
	sprite->setPosition(position);
	if (physics_body != NULL) {
		sprite->setPhysicsBody(physics_body);
		sprite->getPhysicsBody()->setContactTestBitmask(MAX_UINT);
		sprite->getPhysicsBody()->setDynamic(dynamic);
	}
	return sprite;
}
Beispiel #8
0
Sprite * Pip::createPip(const std::string &fileName, float positionY) {
    auto sp = Sprite::create(fileName);
    sp->setPosition(_visibleSize.width , positionY);
    sp->setContentSize(Size(46, 437));
    sp->setPhysicsBody(PhysicsBody::createBox(Size(46, 437)));
    //设置为静态刚体 不受重力影响
    sp->getPhysicsBody()->setDynamic(false);
    //设置碰撞器
    sp->getPhysicsBody()->setContactTestBitmask(1);
    
    return sp;
}
Beispiel #9
0
void Bullet::fadeout(){
    if (!getPhysicsBody()->isEnabled()) {
        return;
    }
    stopAnim();
    getPhysicsBody()->setVelocity(Point::ZERO);
    getPhysicsBody()->setEnable(false);
    const std::function<void()> callback = [&](void){
        m_armature->setOpacity(255);
        getPhysicsBody()->setEnable(true);
        this->hide();
    };
    m_armature->runAction( CCSequence::create(CCFadeOut::create(0.3f),CallFunc::create(callback), NULL) );
}
void BasicScene::natrualWindComes(float dt)
{

	/* To do 在这里添加你想要添加的代码*/
	if (!is_win)
	{
		auto visible_size = Director::getInstance()->getVisibleSize();

		auto hat = getChildByTag(0);

		// Actions to perform
		auto velocity = hat->getPhysicsBody()->getVelocity();
		velocity.y = 200;
		hat->getPhysicsBody()->setVelocity(velocity);
	}
}
Beispiel #11
0
void SceneGameMain::createTopGanTi() //顶部数据
{
    
    
   // auto pSprite=Sprite::createWithTexture(pTexture);
    auto s=Director::getInstance()->getWinSize();
    RenderTexture *pKRender= RenderTexture::create(202, 260);
    pKRender->setPosition(Point(s.width/2, s.height/2));
 //   pKRender->begin();
    pKRender->beginWithClear(255, 255, 255, 255);
    auto pSprite=Sprite::createWithSpriteFrameName("pipetop.png");
    pSprite->cocos2d::Node::setPosition(Point::ZERO);
    pSprite->setAnchorPoint(Point::ZERO);
    pSprite->visit();
    pSprite=Sprite::createWithSpriteFrameName("middle.png");
    pSprite->cocos2d::Node::setPosition(Point(2,64));
    pSprite->setAnchorPoint(Point::ZERO);
    pSprite->visit();
    
    
    
    
    pKRender->end();
   // addChild(pKRender);
    
    
    
    auto pTop=Sprite::createWithTexture(pKRender->getSprite()->getTexture());
    pTop->setPosition(Point(s.width/2, s.height/2+300));
    addChild(pTop);
    auto body = PhysicsBody::createBox(pKRender->getSprite()->getTexture()->getContentSize());
    pTop->setPhysicsBody(body);
    pTop->getPhysicsBody()->setDynamic(false);
}
Beispiel #12
0
bool Edge::init()
{
	if (!Node::init())
	{
		return false;
	}

	auto size = Director::getInstance()->getVisibleSize();

	//Size tSize = Size(size .width,10);

	PhysicsMaterial a;
	a.density = 1.0;
	a.friction = 1.0;
	a.restitution = 0.0;
	
	setPhysicsBody(PhysicsBody::createEdgeBox(size));

	//setContentSize(tSize);
	//setAnchorPoint(Vec2(0, 0));
	//setPosition(0,5);

	getPhysicsBody()->setContactTestBitmask(1);
	return true;
}
void SlideJoint::onEnter()
{
    BaseDemo::onEnter();
    
    auto box1 = createBox(Point(400, 200), Size(100, 100));
    auto box2 = createBox(Point(600, 400), Size(100, 100));
    this->addChild(box1);
    this->addChild(box2);
    
    PhysicsJointLimit * box_joint = PhysicsJointLimit::construct(box1->getPhysicsBody(), box2->getPhysicsBody(), Point(0, 0), Point(0, 0), 120, 200);
    _world->addJoint(box_joint);
    
    Sprite* box = nullptr;
    PhysicsJointLimit* chainJoint_limit = nullptr;
    int chainLen = 10;
    Vector<Sprite*> boxes;
    for (int i = 0; i < chainLen; i++) {
        box = createBox(Point(500 + 40 * i, 600), Size(20, 10));
        this->addChild(box);
        boxes.pushBack(box);
        if (i == 0)
        {
            box->getPhysicsBody()->setDynamic(false);
        }
        if(i > 0)
        {
            chainJoint_limit = PhysicsJointLimit::construct(boxes.at(i-1)->getPhysicsBody(), boxes.at(i)->getPhysicsBody(), Point(10, 0), Point(-10, 0), 10, 20);
            _world->addJoint(chainJoint_limit);
        }
    }
}
Beispiel #14
0
bool Hero::init(){
    
    Sprite::init();
    
    Size s = Size(44, 52);
    
    setContentSize(s);
    setPhysicsBody(PhysicsBody::createBox(s));
    setScale(0.5);

    runAction(RepeatForever::create(FlashTool::readJsonSpriteSheet("hero.json", 0.2f)));
    
    getPhysicsBody()->setRotationEnable(false);
    getPhysicsBody()->setContactTestBitmask(1);
    return true;
    
}
Beispiel #15
0
void Ball::reset(float norm) {
  stop();

  // Throw the ball in a random direction between -45 and 45 degrees.
  auto angle = randInRange(static_cast<float>(-M_PI_4), static_cast<float>(M_PI_4));
  auto velocity = Vect(norm, 0).rotateByAngle(Point::ZERO, angle);
  getPhysicsBody()->setVelocity(velocity);
}
void BackGroud::onUpdate(float dt) {

    log("-----%d", getReferenceCount());
    for (int i = 0; i < _skys.size(); i++) {
        auto sky = _skys.at(i);
        auto floor = _floors.at(i);
        sky->setPositionX(sky->getPositionX() - _speed);
        floor->setPositionX(floor->getPositionX() - _speed);
        if (sky->getPositionX() < 0 - _visibleSize.width /2) {
            _skys.eraseObject(sky);
            _floors.eraseObject(floor);
            i--;
        }
        if (i == _skys.size() -1 && sky->getPositionX() <= _visibleSize.width/2) {
            auto n_sky = createSprite("bg_sky.png", Point(sky->getPositionX() +_visibleSize.width, sky->getPositionY()));
            _layer->addChild(n_sky, 0);
            _skys.pushBack(n_sky);

            auto n_floor = createSprite("bg_floor.png", Point(floor->getPositionX() +_visibleSize.width, floor->getPositionY()));
            n_floor->setPhysicsBody(PhysicsBody::createBox(Size(_visibleSize.width, 64*_scaleY)));
            n_floor->getPhysicsBody()->setDynamic(false);
            //设置碰撞器
            n_floor->getPhysicsBody()->setContactTestBitmask(1);
            _layer->addChild(n_floor, 101);
            _floors.pushBack(n_floor);
        }
    }

//    for (auto it = _bgs.begin(); it != _bgs.end(); it++) {
//        //移动背景
//        (*it)->setPositionX((*it)->getPositionX() - _speed);
//        //判断背景是否已经移除视野 进行删除
//        if ((*it)->getPositionX() < 0 - _visibleSize.width /2) {
//            (*it)->removeFromParent();
//            _bgs.eraseObject(*it);
//        }
//        //判断是否需要新加bg图片
//        if (it +1 == _bgs.end() && (*it)->getPositionX() <=_visibleSize.width/2 -_speed) {
//            auto bg = createSprite(Point((*it)->getPositionX() +_visibleSize.width -_speed, _visibleSize.height /2));
//            _layer->addChild(bg, 0);
//            _bgs.pushBack(bg);
//            break;
//        }
//    }
}
Beispiel #17
0
void Hunter::setFire(Vect fireVect,float angle){
    auto bullet = fireBullet::create();
    bullet->setAnchorPoint(Vect(0.5,0.5));
    bullet->setPosition(posBulletInParent);
    bullet->setFire(angle);
    addChild(bullet);
    bullet->getPhysicsBody()->applyImpulse(fireVect);
    bullet->setScheRemove();
}
Beispiel #18
0
bool Block::init() {
    Sprite::init();
    Size size = Size(rand() % 20 + 5, rand() % 30 + 10);
    Size visibleSize = Director::getInstance()->getVisibleSize();
    setPhysicsBody(PhysicsBody::createBox(size));
    setTextureRect(Rect(0, 0, size.width, size.height));
    setColor(Color3B(0, 0 , 0));
    
    setContentSize(size);
    
//    setPositionX(visibleSize.width + size.width / 2);
    setPositionX(visibleSize.width);
    getPhysicsBody()->setDynamic(false);
    
    scheduleUpdate();
    getPhysicsBody()->setContactTestBitmask(2);
    return true;
}
Beispiel #19
0
bool Rabbit::init(){
    
    Sprite::init();
    initWithFile("game_rabbit.png");
    Size visibleSize = Director::getInstance()->getVisibleSize();
    setPosition(Vec2(visibleSize.width/2,visibleSize.height/2));
    
    Size size = this->getContentSize();
    setPhysicsBody(PhysicsBody::createBox(size));
    
    getPhysicsBody()->setRotationEnable(false);
    getPhysicsBody()->setContactTestBitmask(1);
    
    //test
    getPhysicsBody()->setGravityEnable(true);
    
    return true;

}
Beispiel #20
0
void AISystem::addRobot(Vec2 _pos)
{
	auto robot = EnemyTank::create(enemyPath);
	m_battleLand->addChild(robot);
	robot->setPosition(_pos);
	robot->getPhysicsBody()->setTag(ENEMY_TAG);
	robot->AIStart();

	m_robots.push_back(robot);
}
Beispiel #21
0
bool Hero::init() {
    if (!Sprite::init()) {
        return false;
    }
    
    //设置大小
    auto s = Size(44, 52);
    //添加动画
    runAction(RepeatForever::create(FlashTool::readJsonSpriteSheet("Hero.json", 0.2f)));
    setPhysicsBody(PhysicsBody::createBox(s));
    setContentSize(s);
    
    //不旋转
    getPhysicsBody()->setRotationEnable(false);
    //设置碰撞器
    getPhysicsBody()->setContactTestBitmask(1);

    return true;
}
Beispiel #22
0
void HeroSprite::onKeyReleased(EventKeyboard::KeyCode keyCode, Event* unused_event) {
    switch (keyCode) {
    case EventKeyboard::KeyCode::KEY_UP_ARROW:
		stopActionByTag(10);
    	getPhysicsBody()->resetForces();
		break;
	default:
		break;
	}
}
Beispiel #23
0
void UfoObject::AIUpdate(const float delta) {
  
  
  if((std::abs(target->getPositionX() - getPositionX() )< xAttackDistance)){
    const float yDist = getPositionY() - target->getPositionY();
    if(yDist<yAttackDistance && yDist > -100 && HP>0){
      auto babyTurf = BabyTurfelObject::create();
      babyTurf->setupHitbox(0.1f, 1.0f, 16, 16, 16, 16, false);
      babyTurf->setObjectPositionX(getPositionX() + objectSprite->getTexture()->getPixelsWide()/2);
      babyTurf->setObjectPositionY(getPositionY() + objectSprite->getTexture()->getPixelsWide());
      babyTurf->getPhysicsBody()->setCategoryBitmask((int)PhysicsCategory::Enemy);
      babyTurf->getPhysicsBody()->setCollisionBitmask((int)PhysicsCategory::None);
      babyTurf->getPhysicsBody()->setContactTestBitmask((int)PhysicsCategory::Player|(int)PhysicsCategory::Hazard);
      const float xPow = (float)100.0f/cocos2d::random(1000, 2000) + (target->getPositionX() - getPositionX())/xAttackDistance;
      babyTurf->setVelocityX(xPow * throwSpeedX);
      babyTurf->setVelocityY(throwSpeedY);
      addToGameObjects.pushBack(babyTurf);
    }
  }
}
Beispiel #24
0
void Person::beHit(Vec2 dir)
{
	if(_isDead) return;
	getPhysicsBody()->setVelocity(dir * 0.5);
	_curLife--;
	if(_curLife <= 0)
	{
		_curLife = 0;
		_isDead = true;
	}
}
Beispiel #25
0
void Bullet::onContact(Point contactPoint){
    switch (_bullet_collision) {
        case BULLET_COLLISION_FADEOUT:
            break;
        case BULLET_COLLISION_NORMALBOMB:
        {
            NormalBombModel* model = NormalBombModelManager::getInstance()->getModelByID(_bullet_collision_2);
            NormalBombFactory::create(contactPoint, *model,getPhysicsBody()->getContactTestBitmask(),getPhysicsBody()->getCollisionBitmask());
        }
            break;
        case BULLET_COLLISION_SPLITBOMB:
        {
            SplitBombModel* model = SplitBombModelManager::getInstance()->getModelByID(_bullet_outrange_2);
            SplitBombFactory::create(contactPoint, *model,getPhysicsBody()->getContactTestBitmask(),getPhysicsBody()->getCollisionBitmask());
        }
            break;
        default:
            break;
    }
    fadeout();
}
bool BackGroud::init(cocos2d::Layer *layer, int speed) {
    _speed = speed;
    _visibleSize = Director::getInstance()->getVisibleSize();
    _layer = layer;
    _scaleX = _visibleSize.width /800;
    _scaleY = _visibleSize.height /480;

    //创建一个天空背景
    auto sky = createSprite("bg_sky.png", Point(_visibleSize.width /2,_visibleSize.height - (416 *_scaleY)/2));
    _layer->addChild(sky, 0);
    _skys.pushBack(sky);

    //创建一个地板背景
    auto floor = createSprite("bg_floor.png", Point(_visibleSize.width /2, (64 *_scaleY)/2));
    floor->setPhysicsBody(PhysicsBody::createBox(Size(_visibleSize.width, 64*_scaleY)));
    floor->getPhysicsBody()->setDynamic(false);
    //设置碰撞器
    floor->getPhysicsBody()->setContactTestBitmask(1);
    _layer->addChild(floor, 101);
    _floors.pushBack(floor);

    return true;
}
bool 
GamePlaying::CheckAllPolygonsStopped(){
	for(int t=0;t<=_tag;++t){
		auto node = getChildByTag(t);
		if(node==nullptr){
			continue;
		}
		Vec2 vel=node->getPhysicsBody()->getVelocity(); 
		if(vel.length()>0.001){
			return false;
		}
	}
	return true;
}
void HelloWorld::onEnter(){
    
    Layer::onEnter();
    
    auto bounds = Node::create();
    bounds->setContentSize(visibleSize);
    bounds->setPhysicsBody(PhysicsBody::createEdgeBox(bounds->getContentSize()));
    bounds->getPhysicsBody()->setContactTestBitmask(EDGE_BIT_MASK);
    bounds->setPosition(visibleSize/2);
    addChild(bounds);
    
    addBox(Vec2(visibleSize.width/2, visibleSize.height/2));
    
}
Beispiel #29
0
void Bullet::update(float dt){
    ArmatureBase::update(dt);
    do{
        if(!getPhysicsBody()->isEnabled()){
            break;
        }
        if (m_move_distance>=_range) {
            break;
        }
        m_move_distance+=dt*_speed*bullet_unit_speed;
        if (m_move_distance >= _range) {
            onRangeOut();
        }
    }while (0);
}
// on "init" you need to initialize your instance
bool HelloWorld::init()
{
    //////////////////////////////
    // 1. super init first
    if ( !Layer::init() )
    {
        return false;
    }

    auto visibleSize = Director::getInstance()->getVisibleSize();
    float scale = visibleSize.height /105 *0.06;
    float speed = visibleSize.width /280;

    //创建背景管理器和管道管理器
    _backGround = BackGroud::create(this, speed);
    _backGround->retain();
    _pip = Pip::create(this, speed);
    _pip->retain();
    
    //创造小鸟
    auto bird = Bird::create();
    bird->setPosition(Point(bird->getContentSize().width *3 *scale, visibleSize.height/2));
    addChild(bird ,100);
    //创建碰撞检测器
    auto listener = EventListenerPhysicsContact::create();
    listener->onContactBegin = [this](PhysicsContact & contact){
        this->unschedule("fly");
        auto n_scene = GameOver::createScene();
        Director::getInstance()->replaceScene(n_scene);
        return true;
    };
    Director::getInstance()->getEventDispatcher()->addEventListenerWithSceneGraphPriority(listener, this);
    //创建触摸检测器
    auto touchListener = EventListenerTouchOneByOne::create();
    touchListener->onTouchBegan = [bird, this, visibleSize](Touch * t,Event * e){
        bird->getPhysicsBody()->setVelocity(Vec2(0, visibleSize.height /5.5));
        return false;
    };
    Director::getInstance()->getEventDispatcher()->addEventListenerWithSceneGraphPriority(touchListener, this);
    
    //启动定时器
    schedule([this](float f) {
        this->_backGround->onUpdate(f);
        this->_pip->onUpdate();
    }, 1.0 /30, "fly");
    return true;
}