cocos2d-x CCLayer上精靈的點擊判斷的問題


今天發現的問題,記錄下,對cocos2d坐標轉換的理解還不透徹,看來有必要去學習下OpenGL的基礎知識了。

//使用的2dx是老版本.

1. 平時在CCLayer上放置的CCSprite,判斷是否被點擊到的,我一般這樣做:

//on "init" you need to initialize your instance
bool HelloWorld::init()
{
    bool bRet = false;
    do 
    {
        CC_BREAK_IF(! CCLayer::init());
		
        //Get window size. 
        CCSize size = CCDirector::sharedDirector()->getWinSize();
		
        //pSprite is a CCSprite for test.
        pSprite = CCSprite::spriteWithFile("fjut.png");
        CC_BREAK_IF(! pSprite);
		
        //Place the sprite on the center of the screen	
        pSprite->setPosition(ccp(size.width/2, size.height/2));
		
        this->addChild(pSprite, 0);
        bRet = true;
    } while (0);
	
    this->setIsTouchEnabled(true);
    return bRet;
}
void HelloWorld::registerWithTouchDispatcher()
{
    CCTouchDispatcher::sharedDispatcher()->addTargetedDelegate(this, -1988, true);
}

static CCRect getRect(CCNode* pNode)
{
    CCRect rc;
    rc.origin = pNode->getPosition();
    rc.size = pNode->getContentSize();
    rc.origin.x -= rc.size.width*0.5;
    rc.origin.y -= rc.size.height*0.5;
    return rc;
}

void HelloWorld::ccTouchEnded(CCTouch* pTouch, CCEvent* event)
{
    CCPoint touchLocation = convertTouchToNodeSpace(pTouch);
    if(CCRect::CCRectContainsPoint(getRect(pSprite), touchLocation))
    {
	    printf("我被點中了!\n");
    }
}

bool HelloWorld::ccTouchBegan(CCTouch* touch, CCEvent* event)
{
    return true;
}

2. 要是在CCLayer1上放置CCLayer2(有偏移),再向CCLayer2上放置CCSprite的點擊判斷需要計算偏移量:

eg:

//on "init" you need to initialize your instance
bool HelloWorld::init()
{
    bool bRet = false;
    do 
    {
        CC_BREAK_IF(! CCLayer::init());
        bRet = true;
    } while (0);
	
    this->setIsTouchEnabled(true);
	
    this->testLayer();
	
    return bRet;
}

void HelloWorld::testLayer()
{
    CCLayer* ly = CCLayer::node();
    /*x, y軸各偏移100*/
    ly->setPosition(ccp(100, 100));
    //layer2 add to layer1
    this->addChild(ly);

    pSprite = CCSprite::spriteWithFile("fjut.png");
    pSprite->setPosition(ccp(20, 20));
    ly->addChild(pSprite, 0);
}

void HelloWorld::registerWithTouchDispatcher()
{
    CCTouchDispatcher::sharedDispatcher()->addTargetedDelegate(this, -1988, true);
}

static CCRect getRect(CCNode* pNode)
{
    CCRect rc;
    rc.origin = pNode->getPosition();
    rc.size = pNode->getContentSize();
    /*x, y軸各偏移100*/
    rc.origin.x -= rc.size.width*0.5 - 100;//!!!!
    rc.origin.y -= rc.size.height*0.5 - 100;//!!!!
    return rc;
}

void HelloWorld::ccTouchEnded(CCTouch* pTouch, CCEvent* event)
{
    CCPoint touchLocation = convertTouchToNodeSpace(pTouch);
    if(CCRect::CCRectContainsPoint(getRect(pSprite), touchLocation))
    {
	    printf("我被點中了!\n");
    }
}

bool HelloWorld::ccTouchBegan(CCTouch* touch, CCEvent* event)
{
    return true;
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM