Ejemplo n.º 1
0
CCRect CCTextInput::getRect()
{
    CCSize size = m_designSize;
   
    CCRect rect = CCRectMake(0 - size.width * getAnchorPoint().x, 0 - size.height * getAnchorPoint().y, size.width, size.height);
    return  rect;
}
cocos2d::CCRect GameSprite_Gold::rect()
{
    return CCRectMake(getPositionX() - getContentSize().width * getAnchorPoint().x,
                      getPositionY() - getContentSize().height * getAnchorPoint().y,
                      getContentSize().width, getContentSize().height); // To be able to customize the size of their position with a function rather than inefficient use member variables directly
    
}
Ejemplo n.º 3
0
Scene* Game::createScene(){
    auto scene = Scene::create();
    CCLOG("------------------------GameScene------------------------");
    CCLOG("scene default position:(%.2f,%.2f)",scene->getPosition().x,scene->getPosition().y);
    CCLOG("scene defaule anchor point (%.2f,%.2f),ignoreAnchor:%s" ,
          scene->getAnchorPoint().x,scene->getAnchorPoint().y,scene->isIgnoreAnchorPointForPosition()?"TRUE":"FALSE");
    
    
    
    //注册自身锚点,左下角(0,0),中点(0.5,0.5)
    //动画变形等根据锚点来处理,
    //如果不忽略锚点,则锚点与自身在父容器的position重合,否则0,0点与自身在父容器的position重合
    //scene->setAnchorPoint(Vec2(0.5,0.5));
    //忽略不忽略只影响位置,不影响动画等
    //scene->ignoreAnchorPointForPosition(false);
    
    auto layer = Game::create();
    CCLOG("------------------------GameScene------------------------");
    CCLOG("layer default position:(%.2f,%.2f)",layer->getPosition().x,layer->getPosition().y);
    CCLOG("layer defaule anchor point (%.2f,%.2f),ignoreAnchor:%s" ,
          layer->getAnchorPoint().x,layer->getAnchorPoint().y,layer->isIgnoreAnchorPointForPosition()?"TRUE":"FALSE");
    //layer->ignoreAnchorPointForPosition(false);
    //layer->setAnchorPoint(Vec2(0.5,0.5));
    scene->addChild(layer);
    
    return scene;
}
Ejemplo n.º 4
0
void LayerAndroid::updateLocalTransformAndClip(const TransformationMatrix& parentMatrix,
                                               const FloatRect& clipping)
{
    FloatPoint position(getPosition().x() + m_replicatedLayerPosition.x() - getScrollOffset().x(),
                        getPosition().y() + m_replicatedLayerPosition.y() - getScrollOffset().y());
    float originX = getAnchorPoint().x() * getWidth();
    float originY = getAnchorPoint().y() * getHeight();

    TransformationMatrix localMatrix;

    if (isPositionFixed())
        m_drawTransform.makeIdentity();
    else
        m_drawTransform = parentMatrix;
    m_drawTransform.translate3d(originX + position.x(),
                                originY + position.y(),
                                anchorPointZ());
    m_drawTransform.multiply(m_transform);
    m_drawTransform.translate3d(-originX,
                                -originY,
                                -anchorPointZ());

    m_drawTransformUnfudged = m_drawTransform;
    if (m_drawTransform.isIdentityOrTranslation()
        && surface() && surface()->allowTransformFudging()) {
        // adjust the translation coordinates of the draw transform matrix so
        // that layers (defined in content coordinates) will align to display/view pixels

        // the surface may not allow fudging if it uses the draw transform at paint time
        float desiredContentX = round(m_drawTransform.m41() * m_scale) / m_scale;
        float desiredContentY = round(m_drawTransform.m42() * m_scale) / m_scale;
        ALOGV("fudging translation from %f, %f to %f, %f",
              m_drawTransform.m41(), m_drawTransform.m42(),
              desiredContentX, desiredContentY);
        m_drawTransform.setM41(desiredContentX);
        m_drawTransform.setM42(desiredContentY);
    }

    m_zValue = TilesManager::instance()->shader()->zValue(m_drawTransform,
                                                          getSize().width(),
                                                          getSize().height());

    if (m_haveClip) {
        // The clipping rect calculation and intersetion will be done in content
        // coordinates.
        FloatRect rect(0, 0, getWidth(), getHeight());
        FloatRect clip = m_drawTransform.mapRect(rect);
        clip.intersect(clipping);
        setDrawClip(clip);
    } else {
        setDrawClip(clipping);
    }
    ALOGV("%s - %d %f %f %f %f",
          subclassType() == BaseLayer ? "BASE" : "nonbase",
          m_haveClip, m_clippingRect.x(), m_clippingRect.y(),
          m_clippingRect.width(), m_clippingRect.height());

    setVisible(m_backfaceVisibility || m_drawTransform.inverse().m33() >= 0);
}
Ejemplo n.º 5
0
void ABox::visit(){
	Node::setPosition(ccp(boxBody->GetPosition().x*PTM_RATIO, boxBody->GetPosition().y*PTM_RATIO));

	sprite->setPosition(getPosition());
	sprite->setAnchorPoint(getAnchorPoint());
	sprite->setZOrder(getZOrder());
	sprite->visit();
	if (oldSprite != nullptr)
	{
		oldSprite->setPosition(getPosition());
		oldSprite->setAnchorPoint(getAnchorPoint());
		oldSprite->setZOrder(getZOrder());
		oldSprite->visit();
	}
}
Ejemplo n.º 6
0
bool GameScene::init(){
    if(!Layer::init()){
        return false;
    }
    
    auto sprite = Sprite::create("HelloWorld.png");
    CCLOG("Sprite Defaule Anchor Point: %.0f,%.0f.",sprite->getAnchorPoint().x,sprite->getAnchorPoint().y);
    // position the sprite on the center of the screen
    sprite->setPosition(VisibleRect::center());
    
    // add the sprite as a child to this layer
    this->addChild(sprite, 0);
    
    return true;
}
Ejemplo n.º 7
0
bool MatchJoinList::init()
{
    if (!Layer::init())
    {
        return false;
    }
    auto root = CSLoader::createNode("LayerJoinList.csb");
    this->addChild(root);
    btn_join = dynamic_cast<Button *>(CSLoader::seekNodeByName(root, "image_join"));
    btn_join->addClickEventListener(std::bind(&MatchJoinList::click_join, this));
    btn_cancel_match = dynamic_cast<Button *>(CSLoader::seekNodeByName(root, "btn_cancel_match"));
    btn_cancel_match->setVisible(false);
    btn_cancel_match->addClickEventListener(std::bind(&MatchJoinList::click_cancel_match,this));
    auto listview = dynamic_cast<ListView *>(CSLoader::seekNodeByName(root, "ListView_1"));
    
    auto pSize = listview->getContentSize();
    tableview = TableView::create(this, pSize);
    tableview->setAnchorPoint(listview->getAnchorPoint());
    tableview->setContentOffset(Vec2(0, 0));
    tableview->setVerticalFillOrder(TableView::VerticalFillOrder::TOP_DOWN);
    tableview->setPosition(listview->getPosition());
    tableview->setDelegate(this);
//    tableview->setTag(TAG_TABLEVIEW);
    tableview->setColor(Color3B::RED);
    this->addChild(tableview,255);
    listview->removeFromParentAndCleanup(true);
//    text1 = dynamic_cast<Text *>(CSLoader::seekNodeByName(root, "Text_1")) ;
    
    refresh(nullptr);
    
    dispatch_.register_event(EVENT_GET_TOURNAMENTIFO_LIST,BIND_FUNC(this, MatchJoinList::refresh));
    dispatch_.register_event(EVENT_TO_GET_TOURNAMENTIFO,BIND_FUNC(this, MatchJoinList::send_get_jion_list));
    return true;
}
Ejemplo n.º 8
0
bool LayerComInfoPlayer::init()
{
    if(!Layer::init()) {
        return false;
    }
    
    root_ = CSLoader::createNode("LayerComInfoPlayerPortrait.csb");
    this->addChild(root_);
    
    auto listview = dynamic_cast<ListView*>(CSLoader::seekNodeByName(root_, "listview"));
    
    tableview_ = TableView::create(this, listview->getContentSize());
    tableview_->setAnchorPoint(listview->getAnchorPoint());
    tableview_->setContentOffset(Vec2(0, 0));
    tableview_->setVerticalFillOrder(TableView::VerticalFillOrder::TOP_DOWN);
    tableview_->setPosition(listview->getPosition());
    tableview_->setDelegate(this);
    root_->addChild(tableview_);
    
    listview->removeFromParent();
    
    LayerComInfoTable* layer_table = LayerComInfoTable::create();
    this->addChild(layer_table, 10, "LayerComInfoTable");
    
    auto tf_keyword = dynamic_cast<TextField*>(CSLoader::seekNodeByName(root_, "tf_player_search"));
    tf_keyword_ = GameTools::createEditBoxFromTextField(this, tf_keyword);
    tf_keyword_->setDelegate(this);
    tf_keyword_->setInputMode(EditBox::InputMode::SINGLE_LINE);
    tf_keyword_->setReturnType(EditBox::KeyboardReturnType::SEARCH);
    
    return true;
}
Ejemplo n.º 9
0
bool BattleLayer::TouchBegan(Touch* touch, Event* event)
{
	auto targetCard = static_cast<ReversibleCard*>(event->getCurrentTarget());
	Point locationInNode = touch->getLocation();
	Size s = targetCard->getReversibleCardSize();
	Point pos = targetCard->getPosition();
	Point anchorPoint = targetCard->getAnchorPoint();
	Rect rect = Rect(pos.x - s.width *anchorPoint.x, pos.y - s.height*anchorPoint.y, s.width, s.height);

	//log("locationInNode ..  x = %f, y = %f", locationInNode.x, locationInNode.y);
	//log("pos ..  x = %f, y = %f", pos.x, pos.y);
	//log("anchorPoint ..  x = %f, y = %f", anchorPoint.x, anchorPoint.y);

	if (!m_isOpening && locationInNode.y > (m_openingHeight + 10) && rect.containsPoint(locationInNode) && m_currentCardGroup->size() == 3)
	{
		int idx = 0;
		for (auto& ele : *m_currentCardGroup)
		{
			if (targetCard != ele)
			{
				ele->openCard(m_openCardDuration*idx);
				m_isOpening = true;
				++idx;
			}
			//++idx;  shouldn't add here
		}
		targetCard->openCard(m_openCardDuration*idx, true);
		m_targetCard = targetCard;
	}
	return false;
}
Ejemplo n.º 10
0
bool TimeAttackHUD::init() {
    std::string name = "TimeAttack";
    auto backgroundSprite = sprite(Formatter::toString("%sBackground", name.c_str()));
    addChild(backgroundSprite);
    setContentSize(backgroundSprite->getContentSize());
    backgroundSprite->setPosition(getContentSize().width * getAnchorPoint().x,
                                  getContentSize().height * getAnchorPoint().y);
    auto labelPosition = Point(getContentSize().width * getAnchorPoint().x + 250,
                               getContentSize().height * getAnchorPoint().y + 10);
    
    timerLabel = label("0.000")->position(labelPosition)->color(SCORE_COLOR)->addTo(this);
    
    auto pauseNormalSprite = sprite(Formatter::toString("%sPauseButtonNormal", name.c_str()));
    auto pausePressedSprite = sprite(Formatter::toString("%sPauseButtonPressed", name.c_str()));
    
    auto pauseButton = MenuItemSprite::create(pauseNormalSprite, pausePressedSprite, [=](Ref* sender) {
        playSoundEffect("Click");
        stopTimer();
        EventCustom event("PauseGame");
        _eventDispatcher->dispatchEvent(&event);
    });
    pauseButton->setPosition(Point(labelPosition.x + 220, labelPosition.y));
    auto menu = Menu::create(pauseButton, NULL);
    menu->setPosition(Point::ZERO);
    addChild(menu);
    
    startTimer();
    
    _eventDispatcher->addCustomEventListener("ResumeGame", [=](EventCustom* e) {
        startTimer();
    });
    
    _eventDispatcher->addCustomEventListener("PauseGame", [=](EventCustom* e) {
        stopTimer();
    });
    
    _eventDispatcher->addCustomEventListener("GameWin", [=](EventCustom* e) {
        pauseButton->setEnabled(false);
        stopTimer();
    });
    
    _eventDispatcher->addCustomEventListener("GameLose", [=] (EventCustom* e){
        stopTimer();
    });
    
    return true;
}
Ejemplo n.º 11
0
        void NPC::update(float _dt)
        {
                Entity::update(_dt);
                setSpeed(50.0f);


                //Set the endPosition in relation to their current Position
                if(!hasNewPosition)
                {
                        endPosition.X = getAnchorPoint().X + rand() % 100 * (rand() % 2 ? 1.0f : -1.0f);
                        endPosition.Y = getAnchorPoint().Y + rand() % 100 * (rand() % 2 ? 1.0f : -1.0f);
                        hasNewPosition = true;
                }

                //Reduce the current Time
                timer += _dt;

                //Create a vector to the position
                Vector2 vel = endPosition - getPosition();

                //If they are close dont move any more and pick a new spot
                
                if(vel.length() < 1.0f)
                {
                        hasNewPosition = false;                        
                        return;
                }

                //normalize the vector
                vel.normalize();

                //Scale the vector
                vel *= getSpeed();

                //Set the enemies Velocity
                setVelocity(vel);

                //Multiply the velocity by time and add to the position
                setPosition(getPosition() + vel * _dt);
                if(getTypeID() == NPC_Boy1)
                {
                        vel.normalize();
                        setDirection(getEnumDirection(vel));
                }

        }
Ejemplo n.º 12
0
FramePart* FramePart::clone() const
{
    FramePart* ret = FramePart::createWithTexture(_texture);
    ret->_state = _state;
    ret->setPosition(getPosition());
    ret->setAnchorPoint(getAnchorPoint());
    return ret;
}
Ejemplo n.º 13
0
bool TTouchSprite::isContainedLocation(Touch *pTouch)
{
	Vec2 touchLocation = pTouch->getLocation();

	if (isVisible()) {
		Vec2 local = convertToNodeSpace(touchLocation);
		Rect r = Rect(getPositionX() - getContentSize().width * getAnchorPoint().x,
			getPositionY() - getContentSize().height * getAnchorPoint().y,
			getContentSize().width, getContentSize().height);
		r.origin = Vec2::ZERO;
		if (r.containsPoint(local)) {
			return true;
		}
	}

	return false;
}
Ejemplo n.º 14
0
/**
	@brief		キャンバス初期化
	@param[in]	なし
	@return		なし
*/
void RelayGameLayer::_NextCanvas()
{
	auto oldCanvas = this->getChildByName("Canvas");
	//-----------------------------------------------------
	// 新規キャンバスを既存キャンバスの下に
	auto layerCanvas = LayerCanvas::create();
	if (layerCanvas && layerCanvas->createSprite("canvas.png"))
	{
		this->addChild(layerCanvas, oldCanvas->getLocalZOrder()-1, "NewCanvas");

		layerCanvas->setPosition(oldCanvas->getPosition());
		//layerCanvas->setVisible(false);
	}

	//-----------------------------------------------------
	// DrawNode
	auto drawNode = DrawNode::create();
	{
		drawNode->setAnchorPoint(Vec2::ZERO);
		auto canvas = layerCanvas->getSprite();
		//layerCanvas->addChild(m_pDrawNode, 1);
		drawNode->setPosition(
			-(layerCanvas->getPositionX() - layerCanvas->getAnchorPoint().x*layerCanvas->getContentSize().width),
			-(layerCanvas->getPositionY() - layerCanvas->getAnchorPoint().y*layerCanvas->getContentSize().height)
			);
		canvas->addChild(drawNode, 1, "DrawNode");
	}

	oldCanvas->runAction(
		Sequence::create(
			PageTurn3D::create(0.5f, Size(24.f, 32.f)),
			CallFunc::create([this, oldCanvas, layerCanvas, drawNode](){
				// キャンバスの入れ替え
				//this->removeChild(oldCanvas);
				oldCanvas->setName(oldCanvas->getName() + std::to_string(m_nowPage));
				oldCanvas->setVisible(false);

				layerCanvas->setLocalZOrder(ZOrder::CANVAS);
				layerCanvas->setName("Canvas");
				//--------------------------
				// DrawNode入れ替え
				//m_pDrawNode->release();
				m_pDrawNode = drawNode;
				//--------------------------
				// ページ追加
				m_nowPage++;
				m_touchPoints.push_back(page_t());
				m_nowLine = 0;
				//--------------------------
				// 解答ボックス初期化
				m_pEditBox->setText("");
			}),
			nullptr
		)
	);

}
Ejemplo n.º 15
0
bool Person::ccTouchBegan(CCTouch* touch, CCEvent* event)
{
	CCPoint sLocalPos = convertToNodeSpace(touch->getLocation());  
	CCRect sRC = CCRect(getPositionX() - getContentSize().width * getAnchorPoint().x,  
						   getPositionY() - getContentSize().height * getAnchorPoint().y,  
						   getContentSize().width, getContentSize().height);  
	  
	  
	sRC.origin = CCPointZero;  
	bool isTouched = sRC.containsPoint(sLocalPos);  
	if(isTouched){
		if(lock == 0){
		if(boatState == Constant::STATE_OFFBOAT)//登船
		{
			int count = 0;
			int count2 = 0;
			for(int i = 0; i < record.size(); i++){
				if(record[i]->boatState == 10)
					count++;
			}
			for(int i = 0; i < record.size(); i++){
				if(record[i]->boatState == Constant::STATE_ONBOAT)
					count2++;
			}
			if(count2 == 0){
			if(count < 2){
				if(count == 0){
					boatState =  10;  //新上船	
					boatloc = Constant::ON_BOAT_LEFT;
					this->jumpToBoat(Constant::ON_BOAT_LEFT);
				}
				if(count == 1){
					boatState =  10;  //新上船	
					boatloc = Constant::ON_BOAT_RIGHT;
					this->jumpToBoat(Constant::ON_BOAT_RIGHT);				}
			}
			}
			else{}
		}
	}
		else{}
	}
	return true;
}
Ejemplo n.º 16
0
void Dungeon::dig(Room* from, Room* to)
{
	Point current;
	Point target;
	getAnchorPoint(from, current);
	getAnchorPoint(to, target);
	while (current._x != target._x || current._y != target._y)
	{
		_map[current._x][current._y] = CELL_FLOOR;
		if (target._x > current._x)
			current._x += 1;
		else if (target._x < current._x)
			current._x -= 1;
		else if (target._y > current._y)
			current._y += 1;
		else if (target._y < current._y)
			current._y -= 1;
	}
}
Ejemplo n.º 17
0
void Enemylayer::addEnemys(std::string enemyType,int enemys,float delaytime) //add enemy numbers the same kind
{   
	if (number >= enemys)
	{
		number = 0;
		this->addEnemyRound();
		return;
	}
	CallFunc *callfunc = CallFunc::create([=](){this->addEnemys(enemyType,enemys,delaytime);});
	this->runAction(Sequence::create(DelayTime::create(delaytime),callfunc,nullptr));
	auto enemyinfo = roleInfo.at(enemyType);
	auto roleName = enemyinfo.asValueMap().at("name").asString();
	auto roleHp = enemyinfo.asValueMap().at("hp").asFloat();
	auto roleSpeed = enemyinfo.asValueMap().at("speed").asFloat();
	auto roleMoney = enemyinfo.asValueMap().at("money").asInt();
	auto enemy = Enemy::create(roleName,roleHp,roleSpeed,roleMoney);
	this->addChild(enemy);
 	log("%.2f,%.2f",enemy->getAnchorPoint().x,enemy->getAnchorPoint().y);
	number++;
}
Ejemplo n.º 18
0
bool TSSprite::ccTouchBegan(CCTouch* touch, CCEvent* event)
{
    CCPoint sLocalPos = convertToNodeSpace(touch->getLocation());
    CCRect sRC = CCRect(getPositionX() - getContentSize().width * getAnchorPoint().x,
                           getPositionY() - getContentSize().height * getAnchorPoint().y,
                           getContentSize().width, getContentSize().height);
    
    
    sRC.origin = CCPointZero;
    bool isTouched = sRC.containsPoint(sLocalPos);
    if(isTouched)
    {
        CCLog("点中了!! x:%d y:%d", (int)sLocalPos.x, (int)sLocalPos.y);
        return true;
    }
    else
    {
        CCLog("没点中了!! x:%d y:%d", (int)sLocalPos.x, (int)sLocalPos.y);
        return false;
    }
}
Ejemplo n.º 19
0
bool TextField::hitTest(const Vec2 &pt, const Camera* camera, Vec3* /*p*/) const
{
    if (false == _useTouchArea)
    {
        return Widget::hitTest(pt, camera, nullptr);
    }

    auto size = getContentSize();
    auto anch = getAnchorPoint();
    Rect rect((size.width - _touchWidth) * anch.x, (size.height - _touchHeight) * anch.y, _touchWidth, _touchHeight);
    return isScreenPointInRect(pt, camera, getWorldToNodeTransform(), rect, nullptr);
}
Ejemplo n.º 20
0
SeahorseLayer* SeahorseLayer::clone() const
{
	SeahorseLayer* ret = SeahorseLayer::create();
    ret->setPosition(getPosition());
    ret->setAnchorPoint(getAnchorPoint());

	//Added
	ret->isBye = isBye;
	ret->byePoint = byePoint;
	ret->isHeadToLeft = isHeadToLeft;
	ret->isAttachedToDiver = isAttachedToDiver;

    return ret;
}
void LayerAndroid::dumpLayers(FILE* file, int indentLevel) const
{
    writeln(file, indentLevel, "{");

    writeHexVal(file, indentLevel + 1, "layer", (int)this);
    writeIntVal(file, indentLevel + 1, "layerId", m_uniqueId);
    writeIntVal(file, indentLevel + 1, "haveClip", m_haveClip);
    writeIntVal(file, indentLevel + 1, "isRootLayer", m_isRootLayer);
    writeIntVal(file, indentLevel + 1, "isFixed", m_isFixed);

    writeFloatVal(file, indentLevel + 1, "opacity", getOpacity());
    writeSize(file, indentLevel + 1, "size", getSize());
    writePoint(file, indentLevel + 1, "position", getPosition());
    writePoint(file, indentLevel + 1, "translation", m_translation);
    writePoint(file, indentLevel + 1, "anchor", getAnchorPoint());
    writePoint(file, indentLevel + 1, "scale", m_scale);

    if (m_doRotation)
        writeFloatVal(file, indentLevel + 1, "angle", m_angleTransform);

    if (m_isFixed) {
        writeLength(file, indentLevel + 1, "fixedLeft", m_fixedLeft);
        writeLength(file, indentLevel + 1, "fixedTop", m_fixedTop);
        writeLength(file, indentLevel + 1, "fixedRight", m_fixedRight);
        writeLength(file, indentLevel + 1, "fixedBottom", m_fixedBottom);
        writeLength(file, indentLevel + 1, "fixedMarginLeft", m_fixedMarginLeft);
        writeLength(file, indentLevel + 1, "fixedMarginTop", m_fixedMarginTop);
        writeLength(file, indentLevel + 1, "fixedMarginRight", m_fixedMarginRight);
        writeLength(file, indentLevel + 1, "fixedMarginBottom", m_fixedMarginBottom);
        writePoint(file, indentLevel + 1, "fixedOffset", m_fixedOffset);
        writeIntVal(file, indentLevel + 1, "fixedWidth", m_fixedWidth);
        writeIntVal(file, indentLevel + 1, "fixedHeight", m_fixedHeight);
    }

    if (m_recordingPicture) {
        writeIntVal(file, indentLevel + 1, "picture width", m_recordingPicture->width());
        writeIntVal(file, indentLevel + 1, "picture height", m_recordingPicture->height());
    }

    if (countChildren()) {
        writeln(file, indentLevel + 1, "children = [");
        for (int i = 0; i < countChildren(); i++) {
            if (i > 0)
                writeln(file, indentLevel + 1, ", ");
            getChild(i)->dumpLayers(file, indentLevel + 1);
        }
        writeln(file, indentLevel + 1, "];");
    }
    writeln(file, indentLevel, "}");
}
Ejemplo n.º 22
0
void Node::setPhysicsBody(PhysicsBody* body)
{
    if (body != nullptr)
    {
        body->_node = this;
        body->retain();
        
        // physics rotation based on body position, but node rotation based on node anthor point
        // it cann't support both of them, so I clear the anthor point to default.
        if (!getAnchorPoint().equals(Vec2::ANCHOR_MIDDLE))
        {
            CCLOG("Node warning: setPhysicsBody sets anchor point to Vec2::ANCHOR_MIDDLE.");
            setAnchorPoint(Vec2::ANCHOR_MIDDLE);
        }
    }
    
    if (_physicsBody != nullptr)
    {
        PhysicsWorld* world = _physicsBody->getWorld();
        _physicsBody->removeFromWorld();
        _physicsBody->_node = nullptr;
        _physicsBody->release();
        
        if (world != nullptr && body != nullptr)
        {
            world->addBody(body);
        }
    }
    
    _physicsBody = body;
    
    if (body != nullptr)
    {
        Node* node;
        Scene* scene = nullptr;
        for (node = this->getParent(); node != nullptr; node = node->getParent())
        {
            Scene* tmpScene = dynamic_cast<Scene*>(node);
            if (tmpScene != nullptr && tmpScene->getPhysicsWorld() != nullptr)
            {
                scene = tmpScene;
                break;
            }
        }
        
        updatePhysicsBodyPosition(scene);
        updatePhysicsBodyRotation(scene);
    }
}
Ejemplo n.º 23
0
float UIWidget::getLeftInParent()
{
    float leftPos = 0.0f;
    switch (m_WidgetType)
    {
        case WidgetTypeWidget:
            leftPos = getPosition().x - getAnchorPoint().x * m_size.width;
            break;
        case WidgetTypeContainer:
            leftPos = getPosition().x;
            break;
        default:
            break;
    }
    return leftPos;
}
Ejemplo n.º 24
0
float UIWidget::getBottomInParent()
{
    float bottomPos = 0.0f;
    switch (m_WidgetType)
    {
        case WidgetTypeWidget:
            bottomPos = getPosition().y - getAnchorPoint().y * m_size.height;
            break;
        case WidgetTypeContainer:
            bottomPos = getPosition().y;
            break;
        default:
            break;
    }
    return bottomPos;
}
Ejemplo n.º 25
0
void BBAbstractSceneView::setPosition(const cocos2d::CCPoint &newPosition)
{
	CCPoint p = newPosition;
	float s = getScale();
	CCSize sz = CCSizeMake(m_szOriginal.width * s, m_szOriginal.height * s);
	CCSize szWin = CCDirector::sharedDirector()->getWinSize();
	
	if(p.x > 0) p.x = 0;
	if(p.y > 0) p.y = 0;
	if(p.x < -(sz.width-szWin.width)) p.x = -(sz.width - szWin.width);
	if(p.y < -(sz.height - szWin.height)) p.y = -(sz.height - szWin.height);
		
	CCLayer::setPosition(p);
	CCPoint a = getAnchorPoint();
//	CCLOG("移动: %f, %f, 锚点: %f, %f", p.x, p.y, a.x, a.y);
	
};
Ejemplo n.º 26
0
bool LayerGroupList::init()
{
    if(!BaseLayer::init()) {
        return false;
    }
    
    root_ = CSLoader::createNode("LayerGroup_0.csb");
    this->addChild(root_);
    
    btn_back_ = dynamic_cast<Button*>(CSLoader::seekNodeByName(root_, "btn_back"));
    btn_back_->addClickEventListener(std::bind(&LayerGroupList::click_btn_back, this, std::placeholders::_1));
    //    btn_back_->setVisible(false);
    
    text_title_ = dynamic_cast<Text*>(CSLoader::seekNodeByName(root_, "text_title"));
    text_title_->setString(tools::local_string("title_club", "俱乐部"));
    
    btn_group_search_ = dynamic_cast<Button*>(CSLoader::seekNodeByName(root_, "btn_group_search"));
    btn_group_search_->addClickEventListener(std::bind(&LayerGroupList::click_btn_search, this, std::placeholders::_1));
    
    btn_group_create_ = dynamic_cast<Button*>(CSLoader::seekNodeByName(root_, "btn_group_create"));
    btn_group_create_->addClickEventListener(std::bind(&LayerGroupList::click_btn_add, this, std::placeholders::_1));
    
    auto listview = dynamic_cast<ListView*>(CSLoader::seekNodeByName(root_, "listview"));
    
    tableview_ = TableView::create(this, listview->getContentSize());
    tableview_->setAnchorPoint(listview->getAnchorPoint());
    tableview_->setContentOffset(Vec2(0, 0));
    tableview_->setVerticalFillOrder(TableView::VerticalFillOrder::TOP_DOWN);
    tableview_->setPosition(listview->getPosition());
    tableview_->setDelegate(this);
    tableview_->setClippingToBounds(true);
//    tableview_->setScrollEndedCallback([](){});
//    tableview_->scrollViewDidScroll(<#cocos2d::extension::ScrollView *view#>)
//    tableview_->scrollViewDidScroll(ScrollView* view){};
    
    root_->addChild(tableview_);
    
    listview->removeFromParent();
    requestGroupList();
    group_layer_type_ = LayerGroupList::GROUPLAYERTYPE::GROUPLAYER;
    
    is_select_group_ = false;
    
    return true;
}
Ejemplo n.º 27
0
bool LayerFriendSearch::init()
{
    if(!BaseLayer::init()) {
        return false;
    }
    
    auto root = CSLoader::createNode("LayerGroupSearch.csb");
    this->addChild(root);
    
    auto text_cancel = dynamic_cast<Button*>(CSLoader::seekNodeByName(root, "btn_back"));
    auto text_title = dynamic_cast<Text*>(CSLoader::seekNodeByName(root, "text_title"));
    auto btn_search = dynamic_cast<Button*>(CSLoader::seekNodeByName(root, "btn_search"));
    
    auto tf_keyword = dynamic_cast<TextField*>(CSLoader::seekNodeByName(root, "tf_keyword"));
    tf_keyword_ = GameTools::createEditBoxFromTextField(this, tf_keyword);
    tf_keyword_->setPlaceHolder(tools::local_string("friend_search_word", "请输入玩家昵称或ID").c_str());
    tf_keyword_->setDelegate(this);
    tf_keyword_->setInputMode(EditBox::InputMode::SINGLE_LINE);
    tf_keyword_->setReturnType(EditBox::KeyboardReturnType::SEARCH);
    
    image_search_icon_ = dynamic_cast<ImageView*>(CSLoader::seekNodeByName(root, "image_search_icon"));
    
    text_title->setString(tools::local_string("search_friend", "搜索玩家"));
    
    text_cancel->addClickEventListener(std::bind(&LayerFriendSearch::text_cancel_click, this, std::placeholders::_1));
    
    auto listview = dynamic_cast<ListView*>(CSLoader::seekNodeByName(root, "listview"));
    tableview_ = TableView::create(this, listview->getContentSize());
    tableview_->setAnchorPoint(listview->getAnchorPoint());
    tableview_->setContentOffset(Vec2(0, 0));
    tableview_->setVerticalFillOrder(TableView::VerticalFillOrder::TOP_DOWN);
    tableview_->setPosition(listview->getPosition());
    tableview_->setDelegate(this);
    root->addChild(tableview_);
    
    listview->removeFromParent();
    
    dispatch_.register_event(EVENT_HANDLE_REQ_SEARCH_USER, BIND_FUNC(this, LayerFriendSearch::update_table_view));
    return true;
}
Ejemplo n.º 28
0
///selectively copies parts of the given Sprite
Sprite* StaticHelpers::duplicateSprite(Sprite *sprite)
{
    Sprite* pRet = Sprite::createWithTexture(sprite->getTexture());
    if (sprite->getChildrenCount() > 0) {
        auto children = sprite->getChildren();
        for (auto child : children) {
            auto spriteChild = dynamic_cast<Sprite*>(child);
            if (! spriteChild) continue;
            auto clone = duplicateSprite(spriteChild);
            // can't set boundingBox
            //might need to set textureRect, scale, rotation
            //clone->boundingBox() = spriteChild->boundingBox();
            clone->setContentSize(spriteChild->getContentSize());
            clone->setPosition(spriteChild->getPosition());
            clone->setAnchorPoint(spriteChild->getAnchorPoint());
            clone->setLocalZOrder(spriteChild->getLocalZOrder());
            clone->setTag(spriteChild->getTag());
            pRet->addChild(clone);
        }
    }
    return pRet;
}
Ejemplo n.º 29
0
void Node::setPhysicsBody(PhysicsBody* body)
{
    if (body != nullptr)
    {
        body->_node = this;
        body->retain();
        
        // physics rotation based on body position, but node rotation based on node anthor point
        // it cann't support both of them, so I clear the anthor point to default.
        if (!getAnchorPoint().equals(Point::ANCHOR_MIDDLE))
        {
            CCLOG("Node warning: setPhysicsBody sets anchor point to Point::ANCHOR_MIDDLE.");
            setAnchorPoint(Point::ANCHOR_MIDDLE);
        }
    }
    
    if (_physicsBody != nullptr)
    {
        PhysicsWorld* world = _physicsBody->getWorld();
        _physicsBody->removeFromWorld();
        _physicsBody->_node = nullptr;
        _physicsBody->release();
        
        if (world != nullptr && body != nullptr)
        {
            world->addBody(body);
        }
    }
    
    _physicsBody = body;
    if (body != nullptr)
    {
        Node* parent = getParent();
        Point pos = parent != nullptr ? parent->convertToWorldSpace(getPosition()) : getPosition();
        _physicsBody->setPosition(pos);
        _physicsBody->setRotation(getRotation());
    }
}
Ejemplo n.º 30
0
void HelloWorld::runFx(cocos2d::CCPoint point) {
    CCTextureCache::sharedTextureCache()->addImage("fx/light.png");
	CCSpriteFrameCache::sharedSpriteFrameCache()->addSpriteFramesWithFile("fx/light.plist",CCTextureCache::sharedTextureCache()->textureForKey("fx/light.png"));
	CCArray* sperci=CCArray::create();
	
	for(int i=0;i<18;i++){
	sperci->addObject(CCSpriteFrameCache::sharedSpriteFrameCache()->spriteFrameByName(CCString::createWithFormat("%s%d.png","light",i)->getCString()));
	}
	CCSprite* monst=CCSprite::createWithSpriteFrame((CCSpriteFrame*)sperci->objectAtIndex(0));

	CCAnimation *animation=CCAnimation::createWithSpriteFrames(sperci,0.05f);
	CCAnimate *animate=CCAnimate::create(animation);
	CCCallFuncN *onComplete =  CCCallFuncN::create(this, callfuncN_selector(HelloWorld::runFxCallBack));  
	CCSequence* pse=CCSequence::create(animate,onComplete,NULL);
	monst->setAnchorPoint(getAnchorPoint());
    point.y +=60;
	monst->setPosition(point);
	addChild(monst,100);
	
	//monst->runAction(CCRepeatForever::create(pse));
    monst->setScale(0.5f);
	monst->runAction(pse);
}