簡體   English   中英

如何獲取作為CCScene子級的CCLabel的位置(x,y)?

[英]How to get the location (x,y) of a CCLabel that is a child of a CCScene?

(學習Cocos2D)

創建CCLabel並將其添加到CCLayer后,如下所示:

//From HelloWorldScene.m

// create and initialize a Label
CCLabel* label1 = [CCLabel labelWithString:@"Hello" fontName:@"Marker Felt" fontSize:10];

label1.position =  ccp(35, 435);

// add the label as a child to this Layer
[self addChild: label1];

如何確定用戶何時觸摸了屏幕上的標簽?

首先,您需要注冊場景以接收觸摸事件。 因此,在場景的-(id)init方法中設置self.isTouchEnabled = YES 然后在場景中添加一個方法來注冊觸摸分配器。

- (void)registerWithTouchDispatcher
{
    [[CCTouchDispatcher sharedDispatcher] addTargetedDelegate:self
                                          priority:0
                                          swallowsTouches:YES];
}

當場景獲取ccTouchBegan:withEvent:消息時,從UITouch獲取位置。

- (BOOL)ccTouchBegan:(UITouch *)touch withEvent:(UIEvent *)event
{
    CGPoint location = [touch locationInView:[touch view]];
    location = [[CCDirector sharedDirector] convertToGL:location];
}

最后,您可以通過查看標簽的邊界框來針對標簽的位置測試觸摸的位置。

if (CGRectContainsPoint([label boundingBox], location)) {
    // The label is being touched.
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM