Beispiel #1
0
bool Bullet::init(int iType)
{
	if (!Sprite::init())
	{
		return false;
	}
	if (iType == BulletType::Bullet_Player_main)
	{
		this->initWithFile("bullet/pet_bullet.png");
		this->setTag(ObjectType::TYPE_PLAYER_BULLET);
		auto body = PhysicsBody::createCircle(5.0f);
		body->setCategoryBitmask(Gategorybitmask::GATEGORYBITMASK_PLAYER);
		body->setContactTestBitmask(0xFFFFFFFF);
		body->setCollisionBitmask(Collisionbitmask::COLLISIONBITMASK_PLAYER_BULLET);
		this->setPhysicsBody(body);
		body->setVelocity(Vec2(0, 500));
	}
	else if (iType == BulletType::Bullet_Player_second)
	{
		this->initWithFile("bullet/assisent1_01.png");
		this->setTag(ObjectType::TYPE_PLAYER_BULLET);
		auto body = PhysicsBody::createCircle(5.0f);
		body->setCategoryBitmask(Gategorybitmask::GATEGORYBITMASK_PLAYER);
		body->setContactTestBitmask(0xFFFFFFFF);
		body->setCollisionBitmask(Collisionbitmask::COLLISIONBITMASK_PLAYER_BULLET);
		this->setPhysicsBody(body);
		body->setVelocity(Vec2(0, 1000));
	}
	return true;
}
// on "init" you need to initialize your instance
bool GameScene::init()
{
	//////////////////////////////
	// 1. super init first
	if (!Layer::init())
	{
		return false;
	}

	Size visibleSize = Director::getInstance()->getVisibleSize();
	Vec2 origin = Director::getInstance()->getVisibleOrigin();

	//set background
	auto backgroundSprite = Sprite::create("Background.jpg");
	backgroundSprite->setPosition(Point(visibleSize.width / 2 + origin.x, visibleSize.height / 2 + origin.y));

	//set food
	food = Sprite::create("Food.png");
	srand(time(NULL));
	auto random = rand() % 370 + 30;
	auto random2 = rand() % 270 + 30;
	food->setPosition(Point(random, random2));
	auto foodBody = PhysicsBody::createCircle(food->getContentSize().width / 2);
	foodBody->setCollisionBitmask(FOOD_COLLISION_BITMASK);
	foodBody->setContactTestBitmask(true);
	food->setPhysicsBody(foodBody);

	//set snake particle
	snake = Sprite::create("snake.png");
	snake->setPosition(this->getBoundingBox().getMidX(), this->getBoundingBox().getMidY());
	auto snakeBody = PhysicsBody::createCircle(snake->getContentSize().width / 2);
	snakeBody->setCollisionBitmask(SNAKE_COLLISION_BITMASK);
	snakeBody->setContactTestBitmask(true);
	snake->setPhysicsBody(snakeBody);
	snakeParts.push_back(snake);
	snakeParts.front()->setPosition(100, 100);

	selectSched = schedule_selector(GameScene::update);

	//create the sprites
	this->addChild(backgroundSprite, 0);
	this->addChild(food, 1);
	this->addChild(snakeParts.front(), 2);

	auto eventListener = EventListenerKeyboard::create();
	eventListener->onKeyPressed = CC_CALLBACK_2(GameScene::updateDirection, this);
	this->getEventDispatcher()->addEventListenerWithSceneGraphPriority(eventListener, this);

	auto contactListener = EventListenerPhysicsContact::create();
	contactListener->onContactBegin = CC_CALLBACK_1(GameScene::onContactBegin, this);
	this->getEventDispatcher()->addEventListenerWithSceneGraphPriority(contactListener, this);

	this->schedule(selectSched, 0.1);
	
	return true;
}
void PassGateComponent::onEnter()
{
	Component::onEnter();

	float centerPosition = nextPosY();

	_mainNode = Node::create();
	_mainNode->setPosition(Point(_visibleSize.width / 2, centerPosition));
	this->getOwner()->addChild(_mainNode, 1);

	// center point in the gate for the score updating (check the collision)
	Node* gateCenterNode = Node::create();
	auto gateCenterBody = PhysicsBody::createBox(Size(0, GATE_HEIGHT));
	gateCenterBody->setCollisionBitmask(PASSGATE_CENTER_ID);
	gateCenterBody->setDynamic(false);
	gateCenterBody->setContactTestBitmask(true);
	_mainNode->setPhysicsBody(gateCenterBody);

	// area inside the gate
	Node* gateNode = Node::create();
	auto gateBody = PhysicsBody::createEdgeBox(Size(GATE_WIDTH, GATE_HEIGHT));
	gateBody->setCollisionBitmask(PASSGATE_AREA_ID);
	gateBody->setDynamic(false);
	gateBody->setContactTestBitmask(true);
	gateNode->setPhysicsBody(gateBody);
	_mainNode->addChild(gateNode);

	// height of top 'wall'
	float height1 = _visibleSize.height - SCORE_LAYOUT_BORDER_SIZE * 2 - SCORE_TEXT_SIZE-GATE_HEIGHT;

	// draw graphics of the top 'wall'
	Sprite* topNode = Sprite::create("wall2.png", Rect(Vec2(0, centerPosition), Size(GATE_WIDTH, height1)));
	topNode->setPosition(Point(0, topNode->getBoundingBox().getMaxY()+GATE_HEIGHT/2));
	auto topBody = PhysicsBody::createEdgeBox(topNode->getContentSize());
	topBody->setCollisionBitmask(OBSTACLE_ID);
	topBody->setDynamic(false);
	topBody->setContactTestBitmask(true);
	topNode->setPhysicsBody(topBody);
	_mainNode->addChild(topNode);

	// draw graphics of the bottom 'wall'
	Sprite* bottomNode = Sprite::create("wall2.png", Rect(Vec2(0, centerPosition), Size(GATE_WIDTH, height1)));
	bottomNode->setPosition(Point(0, -(bottomNode->getBoundingBox().getMaxY() + GATE_HEIGHT / 2)));
	auto bottomBody = PhysicsBody::createEdgeBox(bottomNode->getContentSize());
	bottomBody->setCollisionBitmask(OBSTACLE_ID);
	bottomBody->setDynamic(false);
	bottomBody->setContactTestBitmask(true);
	bottomNode->setPhysicsBody(bottomBody);
	_mainNode->addChild(bottomNode);

	//
	auto collisionListener = EventListenerPhysicsContact::create();
	collisionListener->onContactSeparate = CC_CALLBACK_1(PassGateComponent::onContactSeparate, this);
	Director::getInstance()->getEventDispatcher()->addEventListenerWithSceneGraphPriority(collisionListener, gateNode);
}
Beispiel #4
0
void GameLayer::createPips() {
	for (int i = 0; i < 2; i++) {
		auto pipeUp = Sprite::createWithSpriteFrame(
			AtlasLoader::getInstance()->getSpriteFrameByName("pipe_up"));
		auto pipeDown = Sprite::createWithSpriteFrame(
			AtlasLoader::getInstance()->getSpriteFrameByName("pipe_down"));

		pipeUp->setPosition(Vec2(0, -(PIPE_HEIGHT + PIPE_DISTANCE) / 2));
		pipeDown->setPosition(Vec2(0, (PIPE_HEIGHT + PIPE_DISTANCE) / 2));

		//创建物理属性
		auto pipeUpBody = PhysicsBody::createBox(pipeUp->getContentSize(), PHYSICSSHAPE_MATERIAL_DEFAULT, Vec2::ZERO);
		//设置为静态刚体
		pipeUpBody->setDynamic(false);
		pipeUpBody->getShape(0)->setRestitution(0.0f);
		//设置刚体密度
		pipeUpBody->getShape(0)->setDensity(1.0f);
		pipeUpBody->setCategoryBitmask(OBST_MASK);
		pipeUpBody->setCollisionBitmask(BIRD_MASK | OBST_MASK);
		pipeUpBody->setContactTestBitmask(BIRD_MASK | OBST_MASK);
		pipeUp->setPhysicsBody(pipeUpBody);

		auto pipeDownBody = PhysicsBody::createBox(pipeDown->getContentSize(), PHYSICSSHAPE_MATERIAL_DEFAULT, Vec2::ZERO);
		//设置为静态刚体
		pipeDownBody->setDynamic(false);
		pipeDownBody->getShape(0)->setRestitution(0.0f);
		pipeDownBody->getShape(0)->setDensity(1.0f);
		//设置碰撞掩码
		pipeDownBody->setCategoryBitmask(OBST_MASK);
		pipeDownBody->setCollisionBitmask(BIRD_MASK | OBST_MASK);
		pipeDownBody->setContactTestBitmask(BIRD_MASK | OBST_MASK);

		pipeDown->setPhysicsBody(pipeDownBody);

		auto singlePipe = Node::create();
		singlePipe->addChild(pipeUp);
		singlePipe->addChild(pipeDown);

		if (i == 0) {
			singlePipe->setPosition(Vec2(SCREEN_WIDTH * 2 + PIPE_WIDHT / 2, 250));
		} else {
			singlePipe->setPosition(Vec2(SCREEN_WIDTH * 2.5f + PIPE_WIDHT, this->getRandomHeight()));
		}

		singlePipe->setTag(PIPE_NEW);

		this->addChild(singlePipe);
		this->pipes.pushBack(singlePipe);
	}

}
Beispiel #5
0
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;
}
Beispiel #6
0
MayBay * MayBay::Create(){
    MayBay * obj = new MayBay();
    auto SpFrameCache = SpriteFrameCache::getInstance();
    SpFrameCache->addSpriteFramesWithFile("plane/plane.plist");
    if(!obj->initWithSpriteFrame(SpFrameCache->getSpriteFrameByName("planeRed1.png"))){
        CCLOG("Cant not create maybay");
    }
    else{
        Vector<SpriteFrame*> vecFrm(3);
        char str[50]={0};
        for(int i=1; i<=3 ;i++){
            sprintf(str,"planeRed%d.png",i);
            auto spFrm = SpFrameCache->getSpriteFrameByName(str);
            vecFrm.pushBack(spFrm);
            
        }
        auto animation = Animation::createWithSpriteFrames(vecFrm,0.1f);
        auto ani= Animate::create(animation);
        obj->runAction(RepeatForever::create(ani));
    }
    auto physic = PhysicsBody::createBox(Size(Vec2(obj->getContentSize().width-10,obj->getContentSize().height-10)),PhysicsMaterial(1,0,1));
    physic->setCollisionBitmask(0x001);
    physic->setCategoryBitmask(0x001);
    physic->setContactTestBitmask(true);
    physic->setTag(10);
    obj->setPhysicsBody(physic);
    obj->getPhysicsBody()->setGravityEnable(false);
    obj->setFly();
    return obj;
}
Beispiel #7
0
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);
}
Beispiel #8
0
void PlayerComponent::onEnter()
{
	Component::onEnter();

	_movements = new Movements(_startPosition);

	// draw player graphic
	_player = Sprite::create("circle.png");
	_player->setPosition(_movements->getPoint());
	_player->setScale(.5f);
	this->getOwner()->addChild(_player);

	// set the draw nodes
	_drawPointNode = DrawNode::create();
	_player->addChild(_drawPointNode, -1);

	_drawLineNode = DrawNode::create();
	_player->addChild(_drawLineNode, -2);

	// set collision mask
	auto body = PhysicsBody::createCircle(_player->getContentSize().height / 2);
	body->setCollisionBitmask(PLAYER_ID);
	body->setContactTestBitmask(true);
	_player->setPhysicsBody(body);

	//
	auto touchListener = EventListenerTouchOneByOne::create();
	touchListener->onTouchBegan = CC_CALLBACK_2(PlayerComponent::onTouchBegan, this);
	touchListener->onTouchEnded = CC_CALLBACK_2(PlayerComponent::onTouchEnded, this);
	Director::getInstance()->getEventDispatcher()->addEventListenerWithSceneGraphPriority(touchListener, _player);

	auto collisionListener = EventListenerPhysicsContact::create();
	collisionListener->onContactBegin = CC_CALLBACK_1(PlayerComponent::onContactBegin, this);
	Director::getInstance()->getEventDispatcher()->addEventListenerWithSceneGraphPriority(collisionListener, _player);
}
Beispiel #9
0
void GameLayer::createPips() {
    // Create the pips
    for (int i = 0; i < PIP_COUNT; i++) {
        Size visibleSize = Director::getInstance()->getVisibleSize();
        Sprite *pipUp = Sprite::createWithSpriteFrame(AtlasLoader::getInstance()->getSpriteFrameByName("pipe_up"));
        Sprite *pipDown = Sprite::createWithSpriteFrame(AtlasLoader::getInstance()->getSpriteFrameByName("pipe_down"));
        Node *singlePip = Node::create();
        
        // bind to pair
        pipDown->setPosition(0, PIP_HEIGHT + PIP_DISTANCE);
		singlePip->addChild(pipDown, 0, DOWN_PIP);
        singlePip->addChild(pipUp, 0, UP_PIP);
        singlePip->setPosition(visibleSize.width + i*PIP_INTERVAL + WAIT_DISTANCE, this->getRandomHeight());
		auto body = PhysicsBody::create();
		auto shapeBoxDown = PhysicsShapeBox::create(pipDown->getContentSize(),PHYSICSSHAPE_MATERIAL_DEFAULT, Point(0, PIP_HEIGHT + PIP_DISTANCE));
		body->addShape(shapeBoxDown);
		body->addShape(PhysicsShapeBox::create(pipUp->getContentSize()));
		body->setDynamic(false);
		
		//ÉèÖÃÅöײ
		body->setCategoryBitmask(ColliderTypePip);  
		body->setCollisionBitmask(ColliderTypeBird);  
		body->setContactTestBitmask(ColliderTypeBird);  
		
		singlePip->setPhysicsBody(body);
        singlePip->setTag(PIP_NEW);
        
        this->addChild(singlePip);
        this->pips.push_back(singlePip);
    }
}
bool RoleSupplyDoubleGun::init() {
	bool bRet = false;
	do {
		CC_BREAK_IF(!Sprite::initWithSpriteFrameName("ufo1.png"));

		// set physical body
		auto body = PhysicsBody::createBox(getContentSize());
		body->setGroup(PHYSICAL_BODY_SUPPLY_GROUP);
		body->setCategoryBitmask(PHYSICAL_BODY_SUPPLY_BITMASK_CATEGORY);
		body->setContactTestBitmask(PHYSICAL_BODY_SUPPLY_BITMASK_CONTACT_TEST);
		body->setCollisionBitmask(PHYSICAL_BODY_SUPPLY_BITMASK_COLLISION);
		setPhysicsBody(body);

		// set position
		auto bigBoomSize = getContentSize();
		auto winSize = Director::getInstance()->getWinSize();
		int minX = bigBoomSize.width/2;
		int maxX = winSize.width-bigBoomSize.width/2;
		int rangeX = maxX-minX;
		int actualX = (rand()%rangeX)+minX;
		setPosition(Point(actualX, winSize.height+bigBoomSize.height/2));

		// run action
		auto move1 = MoveBy::create(0.5, Point(0, -150));
		auto move2 = MoveBy::create(0.3, Point(0, 100));
		auto move3 = MoveBy::create(1.0, Point(0, 0-winSize.height-bigBoomSize.height/2));
		auto actionDone = RemoveSelf::create(true);
		auto sequence = Sequence::create(move1, move2, move3, actionDone, nullptr);
		runAction(sequence);

		bRet = true;
	} while (0);

	return bRet;
}
Beispiel #11
0
void GameScreen::spawnAsteroid(float dt)
{
    Size visibleSize = Director::getInstance()->getVisibleSize();
    Point origin = Director::getInstance()->getVisibleOrigin();

    int asteroidIndex = (arc4random() % 3) + 1;
    __String* asteroidString = __String::createWithFormat("GameScreen/Asteroid_%i.png", asteroidIndex);

    Sprite* tempAsteroid = Sprite::create(asteroidString->getCString());

    int xRandomPosition = (arc4random() % (int)(visibleSize.width - (tempAsteroid->getContentSize().width / 2))) + (tempAsteroid->getContentSize().width / 2);

    tempAsteroid->setPosition(
        Point(xRandomPosition + origin.x,
              -tempAsteroid->getContentSize().height + origin.y));

    asteroids.push_back(tempAsteroid);

    auto body = PhysicsBody::createCircle(asteroids[asteroids.size() - 1]->getContentSize().width / 2);
    body->setContactTestBitmask(true);
    body->setDynamic(true);
    asteroids[asteroids.size() - 1]->setPhysicsBody(body);
    
    this->addChild(asteroids[asteroids.size() - 1], -1);
}
Beispiel #12
0
void Paddle::createPhysicsBody() {
  auto bodySize = getContentSize();

  auto width2 = bodySize.width / 2;
  auto width4 = width2 / 2;
  auto width8 = width4 / 2;
  auto height2 = bodySize.height / 2;
  auto height4 = height2 / 2;
  auto height8 = height4 / 2;

  // Create this oval shape so that, when the ball bounces closer to the edges,
  // its direction changes slightly.
  std::array<Point, 12> bodyPoints = {
    Point(width4,           height2),
    Point(width2 - width8,  height2 - height8),
    Point(width2,           height8),
    Point(width2,           -height8),
    Point(width2 - width8,  -height2 + height8),
    Point(width4,           -height2),
    Point(-width4,          -height2),
    Point(-width2 + width8, -height2 + height8),
    Point(-width2,          -height8),
    Point(-width2,          height8),
    Point(-width2 + width8, height2 - height8),
    Point(-width4,          height2)
  };

  auto body = PhysicsBody::createPolygon(bodyPoints.data(), bodyPoints.size(), MATERIAL);
  body->setDynamic(false);
  body->setContactTestBitmask(BITMASK_CONTACT_TEST);

  setPhysicsBody(body);
}
BossBullet * BossBullet::createBossBullet3()
{
	BossBullet * bossBullet3 = new BossBullet();
	if (bossBullet3 && bossBullet3->initWithFile("GameScreen/ss_boss1_attack3.png", Rect(0, 0, 36, 36)))
	{
		//Create and run animation
		Vector<SpriteFrame*> animFrames(5);
		char str[100] = { 0 };
		for (int i = 0; i < 5; i++)
		{
			sprintf(str, "GameScreen/ss_boss1_attack3.png");
			auto frame = SpriteFrame::create(str, Rect(36 * i, 0, 36, 36)); //we assume that the sprites' dimentions are 30x30 rectangles.
			animFrames.pushBack(frame);
		}
		auto animation = CCAnimation::createWithSpriteFrames(animFrames, 0.15f, 100000);
		auto animate = CCAnimate::create(animation);
		//make body for collisions
		cocos2d::Size size(36, 36);
		auto bossBulletBody = PhysicsBody::createBox(size);
		bossBulletBody->setCollisionBitmask(0x000006);
		bossBulletBody->setContactTestBitmask(true);
		bossBullet3->setPhysicsBody(bossBulletBody);
		bossBulletBody->setTag(60);
		bossBullet3->runAction(animate);
		bossBullet3->initBullet();
		bossBullet3->setTag(60);
		return bossBullet3;
	}

	CC_SAFE_DELETE(bossBullet3);
	return NULL;
}
void Coin3::spawnCoin3(cocos2d::Layer * layer)
{
    auto coin=Sprite::create("Candy (3).png");
    const float SCALE_TO_DEVICE = Director::getInstance()->getVisibleSize().width / DES_RES_X;
    coin->setScale(SCALE_TO_DEVICE * 2);
    //coin->setScale(2, 2);
    auto ran=CCRANDOM_0_1();
    auto posi_x=origin.x+coin->getContentSize().width* SCALE_TO_DEVICE/2+ran*(visibleSize.width-coin->getContentSize().width* SCALE_TO_DEVICE);
    auto posi_y=origin.y+visibleSize.height;
    
    auto body=PhysicsBody::createBox(coin->getContentSize()*2* SCALE_TO_DEVICE);
    
    body->setDynamic(false);
    body->setCollisionBitmask(COIN3_COLLISION_BITMASK);
    body->setContactTestBitmask(COIN3_CONTACT_BITMASK);
    coin->setPhysicsBody(body);
    
    coin->setPosition(Point(posi_x,posi_y));
    layer->addChild(coin,7);
    auto move_dis=visibleSize.height+coin->getContentSize().height* SCALE_TO_DEVICE+50;
    auto move_duration=COIN3_SPEED*move_dis;
    auto coin_move=MoveBy::create(move_duration,Point(0,-move_dis));
    coin->runAction(Sequence::create(coin_move,RemoveSelf::create(true),nullptr));
    
}
Beispiel #15
0
Bird::Bird(cocos2d::Layer *layer){
	visibleSize = Director::getInstance()->getVisibleSize();
	origin = Director::getInstance()->getVisibleOrigin();

	flappyBird = Sprite::create("Will.png");
	flappyBird->setPosition(Point(visibleSize.width / 2 + origin.x, visibleSize.height / 2 + origin.y));

	willLocationX = flappyBird->getPositionX();
	willLocationY = flappyBird->getPositionY();

	auto flappyBody = PhysicsBody::createBox(Size(flappyBird->getContentSize().width, flappyBird->getContentSize().height), PhysicsMaterial(0, 1, 0));
	flappyBody->setGravityEnable(false);
	flappyBird->setPhysicsBody(flappyBody);

	layer -> addChild(flappyBird, 100);

	flappyBody->setCollisionBitmask(BIRD_COLLISION_BITMASK);
	flappyBody->setContactTestBitmask(true);
	flappyBody->setMass(1);

	//isFalling = true;

	flappyBird->getPhysicsBody()->setVelocityLimit(300);
	
}
Beispiel #16
0
Sprite* Stage::addPhysicsBody(cocos2d::TMXLayer *layer, cocos2d::Vec2 &coordinate)
{
    // タイル1枚の大きさを取り出す
    auto tileSize = _tiledMap->getTileSize();
    
    // タイルのスプライトを取り出す
    auto sprite = layer->getTileAt(coordinate);
    if (sprite) {
        // タイルのIDを取り出す
        auto gid = layer->getTileGIDAt(coordinate);
        // タイルのプロパティをmapで取り出す
        auto property = _tiledMap->getPropertiesForGID(gid);
        if (property.isNull() || property.getType() != Value::Type::MAP) {
            return nullptr;
        }
        auto properties = property.asValueMap();
        // プロパティの中からcategoryの値をintとして取り出す
        auto category = properties.at("category").asInt();
        
        auto material = PhysicsMaterial();
        material.friction = 0;
        material.restitution = 0.1;
        
        // 剛体を設置する
        auto physicsBody = PhysicsBody::createBox(sprite->getContentSize(), material);
        // 剛体を固定する
        physicsBody->setDynamic(false);
        // 剛体にカテゴリをセットする
        physicsBody->setCategoryBitmask(category);
        // 剛体と接触判定を取るカテゴリを指定する
        physicsBody->setContactTestBitmask(static_cast<int>(TileType::PLAYER));
        // 剛体と衝突を取るカテゴリを指定する
        physicsBody->setCollisionBitmask(static_cast<int>(TileType::PLAYER));
        
        // アニメーションを付ける
        // プロパティにanimationの値があったら
        if (!properties["animation"].isNull()) {
            auto animationSprite = properties["animation"].asString();
            auto animationCount = properties["animationCount"].asInt();
        
            sprite->removeFromParent();
            this->addChild(sprite);
            
            Vector<SpriteFrame *> frames;
            auto scale = 0.5;
            for (int i = 0; i < animationCount; ++i) {
                auto frame = SpriteFrame::create(animationSprite, Rect(tileSize.width * i * scale, 0, tileSize.width * scale, tileSize.height * scale));
                frames.pushBack(frame);
            }
            auto animation = Animation::createWithSpriteFrames(frames);
            animation->setDelayPerUnit(0.15);
            sprite->runAction(RepeatForever::create(Animate::create(animation)));
        }
        sprite->setAnchorPoint(Vec2::ANCHOR_MIDDLE);
        sprite->setPhysicsBody(physicsBody);
        
        return sprite;
    }
    return nullptr;
}
Beispiel #17
0
bool Player::init()
{
	if (!Sprite::initWithFile("graphics/luk_sprite.png"))
	{
		return false;
	}
	this->setAnchorPoint(Vec2::ANCHOR_MIDDLE);

	cocos2d::Point PBox[8]{cocos2d::Point(-2, -12), cocos2d::Point(-4, -10), cocos2d::Point(-4, -2), cocos2d::Point(-2, 0), cocos2d::Point(2, 0), cocos2d::Point(4, -2), cocos2d::Point(4, -10), cocos2d::Point(2, -12)};
	playerRect = Rect();
	auto body = PhysicsBody::createPolygon(PBox, 8);
	body->setEnable(true);
	body->setDynamic(true);
	body->setGravityEnable(true);
	body->setRotationEnable(false);
	body->setVelocityLimit(30.0);
	body->setCategoryBitmask(static_cast<int>(Stage::TileType::PLAYER));
	//BLOCKSとの接触判定をON
	body->setCollisionBitmask(static_cast<int>(Stage::TileType::EMPTY));
	body->setContactTestBitmask(static_cast<int>(Stage::TileType::BLOCKS));

	//body->setContactTestBitmask(INT_MAX);

	this->setPhysicsBody(body);

	this->scheduleUpdate();
	return true;
}
Beispiel #18
0
bool Player::init()
{
	if (!Sprite::initWithFile("graphics/luk_sprite.png"))
	{
		return false;
	}



	//Point PBox[8]{Point(-2, -12), Point(-4, -10), Point(-4, -2), Point(-2, 0), Point(2, 0), Point(4, -2), Point(4, -10), Point(2, -12)};
	Point PBox[4]{Point(-4, -12), Point(-4, 0), Point(4, 0), Point(4, -12)};

	//auto body = PhysicsBody::createEdgePolygon(PBox, 4,PHYSICSBODY_MATERIAL_DEFAULT,0.5f);
	auto body = PhysicsBody::createPolygon(PBox, 4);
	body->setEnable(true);
	body->setDynamic(true);
	body->setGravityEnable(true);
	body->setRotationEnable(false);
	body->setVelocityLimit(30.0);
	body->setCategoryBitmask(static_cast<int>(Stage::TileType::PLAYER));
	//BLOCKSとの接触判定をON
	//body->setCollisionBitmask(static_cast<int>(Stage::TileType::BLOCKS));
	body->setCollisionBitmask(static_cast<int>(Stage::TileType::NONE));
	body->setContactTestBitmask(static_cast<int>(Stage::TileType::BLOCKS));

	//body->setContactTestBitmask(INT_MAX);

	this->setPhysicsBody(body);

	this->setAnchorPoint(Vec2::ANCHOR_MIDDLE);
	this->scheduleUpdate();
	return true;
}
Beispiel #19
0
Balloon* Balloon::createWithForce(Point* pos, Point* force)
{
    Balloon* b = new Balloon();

    if (b && b->initWithFile("balloon.png"))
    {
        // Set auto release.
        b->autorelease();
        // Set Scale
        b->setScale(0.15f);

        // Set Position
        b->setPosition(*pos);

        // CHANGE TO A DEFINED NUMBER AFTER
        //this->setTag(0);
        auto body = PhysicsBody::createCircle(b->getBoundingBox().size.width/2.5f);
        body->setMass(1);
        body->setDynamic(true);
        body->setContactTestBitmask(2);
        body->setCategoryBitmask(0x01); //0001
        b->setPhysicsBody(body);

        // give forces
        b->getPhysicsBody()->applyImpulse(*force);

        b->schedule(schedule_selector(Balloon::update));

        return b;
    }
    CC_SAFE_DELETE(b);

    return NULL;
}
Beispiel #20
0
void FireBall::spawnFireBall(cocos2d::Layer * layer)
{
    auto FireBall=cocos2d::Sprite::create("FireBall.png");
    auto ran=CCRANDOM_0_1();
    auto posi_x=ran*visibleSize.width+origin.x;
    auto posi_y=origin.y+visibleSize.height+FireBall->getContentSize().height;
    
    Vector<SpriteFrame*> fireball_an(4);
    fireball_an.pushBack(SpriteFrame::create("FireBall.png", Rect(0,0,58,96)));
    fireball_an.pushBack(SpriteFrame::create("FireBall_2.png", Rect(0,0,58,96)));
    fireball_an.pushBack(SpriteFrame::create("FireBall.png", Rect(0,0,58,96)));
    fireball_an.pushBack(SpriteFrame::create("FireBall_3.png", Rect(0,0,58,96)));
    auto ann=Animation::createWithSpriteFrames(fireball_an,0.1f);
    auto anim_ll=Animate::create(ann);
    auto anim_l=RepeatForever::create(anim_ll);
    FireBall->runAction(anim_l);

    
    auto FireBall_body=cocos2d::PhysicsBody::createBox(FireBall->getContentSize());
    
    FireBall_body->setDynamic(false);
    FireBall_body->setCollisionBitmask(FIREBALL_COLLISION_BITMASK);
    FireBall_body->setContactTestBitmask(FIREBALL_CONTACT_BITMASK);
    FireBall->setPhysicsBody(FireBall_body);
    
    FireBall->setPosition(Point(posi_x,posi_y));
    layer->addChild(FireBall,102);
    auto move_dis=visibleSize.height+FireBall->getContentSize().height+130;
    auto move_duration=FIREBALL_SPEED*move_dis;
    auto FireBall_move=cocos2d::MoveBy::create(move_duration,Point(0,-move_dis));
    FireBall->runAction(Sequence::create(FireBall_move,RemoveSelf::create(true),nullptr));
    
}
Beispiel #21
0
Bike * Bike::create(Vec2 position, GameStates & gameState)
{
	std::shared_ptr<GameData> ptr = GameData::sharedGameData();

	auto spritecache = SpriteFrameCache::getInstance();	

	Bike* pSprite = new Bike(gameState);
	if (pSprite && pSprite->initWithFile("GameScreen/bikepic.png"))
	{
		pSprite->autorelease();

		pSprite->initOptions(position);
		cocos2d::Size size(35, 138);
		auto towerBody = PhysicsBody::createBox(size);
		towerBody->setCollisionBitmask(0x000002);
		towerBody->setContactTestBitmask(true);

		pSprite->setPhysicsBody(towerBody);

		return pSprite;
	}

	CC_SAFE_DELETE(pSprite);
	return NULL;
}
Beispiel #22
0
bool DamagePowerUp::init() 
{
    if ( !PowerUp::init() ){
        return false;
    }
    
    std::ostringstream stream;
    stream << "powerups/DP" << ((int)_damageLevel) << ".png";
    setTexture(stream.str());
    setOpacity(0);
    auto fadeIn = FadeIn::create(1.0f);
    runAction(fadeIn);
    
    // [[-- sets the physic body
    auto physicBody = PhysicsBody::createBox( Size( getContentSize().width , getContentSize().height ) ,
                                              PhysicsMaterial(0, 0.02, 0) );
    physicBody->setCategoryBitmask(Type::POWERUP);
    physicBody->setCollisionBitmask( Entity::Type::SHIP );
    physicBody->setContactTestBitmask(Type::SHIP);
    
    //physicBody->setTag();
    setPhysicsBody( physicBody );
    // --]]
    
    _stats.damage = 5;
    
    // Tells Cocos2d-x to call the Node's update function
    scheduleUpdate();
    
    return true;
}
Beispiel #23
0
Truck * Truck::create(Vec2 position, GameStates & gameState)
{
	std::shared_ptr<GameData> ptr = GameData::sharedGameData();

	auto spritecache = SpriteFrameCache::getInstance();
	spritecache->addSpriteFramesWithFile(ptr->m_textureAtlasPlistFile);		

	Truck* pSprite = new Truck(gameState);
	if (pSprite->initWithSpriteFrameName(ptr->m_truck))
	{
		pSprite->autorelease();

		pSprite->initOptions(position);

		cocos2d::Size size(70, 200);
		auto towerBody = PhysicsBody::createBox(size);
		towerBody->setCollisionBitmask(0x000002);
		towerBody->setContactTestBitmask(true);
		//towerBody->setDynamic(false);

		pSprite->setPhysicsBody(towerBody);

		return pSprite;
	}

	CC_SAFE_DELETE(pSprite);
	return NULL;
}
Beispiel #24
0
Fighter* Fighter::createWithSpriteFrameName(const char* spriteFrameName)
{
	Fighter* fighter=new Fighter();
	
	if(fighter&&fighter->initWithSpriteFrameName(spriteFrameName)){
		fighter->autorelease();

		ParticleSystem *ps=ParticleSystemQuad::create("particle/fire.plist");
	
		//·É»úÏÂÃæ
		ps->setPosition(Vec2(fighter->getContentSize().width/2,0));
	//	ps->setRotation(180.0f);
		ps->setScale(0.5f);
		fighter->addChild(ps);
		////////////////////////////////////////////////////////////////////
		Vec2 verts[]={
			Vec2(-43.5,15.5),
			Vec2(-23.5,33),
			Vec2(28.5,34),
			Vec2(48,17.5),
			Vec2(0,-39.5)};

		auto body=PhysicsBody::createPolygon(verts,5);

		body->setCategoryBitmask(0x01);
		body->setCollisionBitmask(0x02);
		body->setContactTestBitmask(0x01);

		fighter->setPhysicsBody(body);
		return fighter;

	}
	CC_SAFE_DELETE(fighter);
	return nullptr;
}
Beispiel #25
0
void Character::InitCharacterSprite(char* char_name){
    Isbomb=false;
    Char_name=char_name;
    this->character=CCSprite::create(char_name);
    
    
    
    storm = Sprite::create("k.png");
    storm->setVisible(false);
    storm->setScale(0.6f);
    auto stormBody = PhysicsBody::createBox( storm->getContentSize());
    // stormBody->setDynamic(false);
    stormBody->setCollisionBitmask( STORM_COLLISION_BITMASK );
    stormBody->setCategoryBitmask(8);
    stormBody->setContactTestBitmask(1);
    //    //stormBody->
    storm->setPhysicsBody(stormBody);
    //stormBody->
    
    
    numberOfBomb=0;
    
    this->addChild(storm);
    this->addChild(character);
}
Beispiel #26
0
Coin * Coin::create(Vec2 position, GameStates & gameState)
{
	std::shared_ptr<GameData> ptr = GameData::sharedGameData();

	auto spritecache = SpriteFrameCache::getInstance();
	spritecache->addSpriteFramesWithFile(ptr->m_textureAtlasPlistFile);		

	Coin* pSprite = new Coin(gameState);
	if (pSprite->initWithSpriteFrameName(ptr->m_coinFile))
	{
		pSprite->autorelease();
		

		pSprite->initOptions(position);

		pSprite->addEvents();
		pSprite->setTag(30);

		auto towerBody = PhysicsBody::createBox(pSprite->getContentSize());
		towerBody->setCollisionBitmask(0x000003);
		towerBody->setContactTestBitmask(true);
		towerBody->setTag(30);
		//towerBody->setDynamic(false);

		pSprite->setPhysicsBody(towerBody);

		return pSprite;
	}

	CC_SAFE_DELETE(pSprite);
	return NULL;
}
Hero::Hero(cocos2d::Layer *layer)
{
    const float SCALE_TO_DEVICE = Director::getInstance()->getVisibleSize().width / DES_RES_X;
    
    visibleSize = Director::getInstance()->getVisibleSize();
    origin = Director::getInstance()->getVisibleOrigin();
    move_x=origin.x+visibleSize.width/2;
    move_y=origin.y+visibleSize.height/2;
    M_hero=Sprite::create("Jump (1).png");
    M_hero->setScale(SCALE_TO_DEVICE);
    M_hero->setPosition(Point(origin.x + visibleSize.width / 2, origin.y + visibleSize.height * 0.2));
    auto size=M_hero->getContentSize() * SCALE_TO_DEVICE;
    size.height=size.height*0.62;
    size.width=size.width*0.62;
    auto hero_b = PhysicsBody::createBox(size);
    //hero_b->setDynamic(false);
    hero_b->setRotationEnable(false);
    M_hero->setPhysicsBody(hero_b);
    hero_b->setCollisionBitmask(HERO_COLLISION_BITMASK);
    hero_b->setContactTestBitmask(HERO_CONTACT_BITMASK);
    Vector<SpriteFrame*> trix_ani(4);
    trix_ani.pushBack(SpriteFrame::create("Jump (1).png", Rect(0,0,140,192)));
    trix_ani.pushBack(SpriteFrame::create("Jump (2).png", Rect(0,0,140,192)));
    trix_ani.pushBack(SpriteFrame::create("Jump (3).png", Rect(0,0,140,192)));
    trix_ani.pushBack(SpriteFrame::create("Jump (4).png", Rect(0,0,140,192)));
    auto ani=Animation::createWithSpriteFrames(trix_ani,0.1f);
    auto anim_rr=Animate::create(ani);
    auto anim_r=RepeatForever::create(anim_rr);
    M_hero->runAction(anim_r);
    
    layer->addChild(M_hero, 100000);
    
    
}
Beispiel #28
0
void Hanhtinh::spawn_hanhtinh( float dt )
{
	Size visibleSize = Director::getInstance()->getVisibleSize();
	Point origin = Director::getInstance()->getVisibleOrigin();

	int hanhtinh_index = (rand() % 2) + 1;
	__String* hanhtinh_String = __String::createWithFormat("GameScreen/Asteroid_%i.png", hanhtinh_index);
	Sprite* tempHanhtinh = Sprite::create(hanhtinh_String->getCString());

	int yRandomPosition = (rand() % (int)(visibleSize.height - (tempHanhtinh->getContentSize().height / 2))) + 
		(tempHanhtinh->getContentSize().height / 2);

	//int xRandomPosition =  (rand() % (int)(visibleSize.width/2));

	tempHanhtinh->setPosition(Point( visibleSize.width, yRandomPosition ));
	hanhtinh.push_back(tempHanhtinh);

	auto hanhtinh_body = PhysicsBody::createCircle( hanhtinh[hanhtinh.size() -1 ]->getContentSize().width /2 );
	hanhtinh_body->setContactTestBitmask(true);
	hanhtinh_body->setDynamic(true);
	hanhtinh[hanhtinh.size() -1 ]->setPhysicsBody(hanhtinh_body);
	hanhtinh[hanhtinh.size() -1]->setTag(TAG_HANHTINH);
	this->addChild(hanhtinh[hanhtinh.size() - 1], -1);

}
Beispiel #29
0
void Ball::spawnBall(cocos2d::Layer *layer, Point throwerPosition, int throwerGrowth,/* int type, float speed,*/ int way)
{
	//Point throwerPosition = thrower->getPosition();
    CCLOG( "SPAWN BALL" );
    
    auto ball = Sprite::create( IMG_BALL );
    
    auto ballPosition = throwerPosition;
	ballPosition.y += way*throwerGrowth;

	ball->setPosition(ballPosition);
	ball->setScale(1.3f);
    
	auto ballBody = PhysicsBody::createCircle(ball->getContentSize().width/2);
	ballBody->setCollisionBitmask(BALL_COLLISION_BITMASK);
	ballBody->setContactTestBitmask(true);
	ball->setPhysicsBody(ballBody);
	ball->setName("ball");
    
	layer->addChild(ball, 100);
    
    auto ballAction = MoveBy::create( (1.0f/BALL_MOVEMENT_SPEED) * visibleSize.height * ball->getScale(), Point( 0, way*visibleSize.height * 1.5 ) );
    
	ball->runAction(ballAction);
}
Beispiel #30
0
void Devil::InitSprite()
{
	auto body = PhysicsBody::createBox(this->getContentSize(), PhysicsMaterial(100, 1, 1));
	body->setDynamic(true);
	body->setGravityEnable(false);
	body->setRotationEnable(false);
	body->setCollisionBitmask(MONSTER_BODY_COLLISION_BITMASK);
	body->setContactTestBitmask(true);
	this->setPhysicsBody(body);
	this->setUserData(this);

	hpBgSpr = Sprite::create("Monster/hpBg.png");
	this->addChild(hpBgSpr, ZINDEX_MONSTER_HP);
	hpCurrentSpr = Sprite::create("Monster/hpCurrent.png");
	this->addChild(hpCurrentSpr, ZINDEX_MONSTER_HP);
	auto origin = Director::getInstance()->getVisibleOrigin();
	hpBgSpr->setPosition(Vec2(this->getContentSize().width / 2, this->getPosition().y + this->getContentSize().height + hpBgSpr->getContentSize().height / 2));
	hpCurrentSpr->setPosition(hpBgSpr->getPosition());
	hpBgSpr->setOpacity(0);
	hpCurrentSpr->setOpacity(0);

	fury = CSLoader::createNode("Effect/Rage/Rage.csb");
	fury->setPosition(this->getContentSize().width * 0.5f, this->getContentSize().height * 0.5f);
	this->addChild(fury);
	fury->setVisible(false);

	auto visibleSize = Director::getInstance()->getVisibleSize();
	d = Dragon::create(layer);
	d->setPosition(visibleSize.width*0.7f, visibleSize.height*0.7f);
	layer->addChild(d, ZINDEX_MONSTER_SPRITE);
	d->scheduleUpdate();

}