[英]cocos2d for iPhone - Touch no longer works correctly after scale
我對將Cocos2d用於iPhone相當陌生,並且觸摸位置存在問題。 目前,我只是試圖觸摸和移動屏幕上的一個精靈,當不移動圖層以及平移圖層(在我的情況下,在X方向上更改self.position)時,此方法都可以正常工作,但是當我縮放時我的圖層(例如:self.scale = .5),觸摸不再移動精靈。 我已經做了很多論壇搜索/谷歌搜索,我認為我的問題與我的坐標變換(節點空間/世界空間等)有關,但是我不確定100%。 我確實注意到,在縮放時,如果我單擊精靈沒有縮放的位置,則可以移動精靈。 這使我相信我的變換沒有考慮到縮放比例。
這是我當前用於獲取觸摸位置的坐標轉換代碼:
- (void)ccTouchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
UITouch *myTouch = [touches anyObject];
CGPoint location = [myTouch locationInView:[myTouch view]];
location = [self convertToNodeSpace:location];
location = [[CCDirector sharedDirector] convertToGL:location];
}
這是用於檢查位置(與上面相同的位置變量)是否接觸到精靈的代碼,盡管我更確定該代碼是正確的,誰知道!
for (CCSprite *sprite in movableSprites) {
if (CGRectContainsPoint(sprite.boundingBox, touchLocation)) {
NSLog(@"Woohoo, you touched a sprite!");
break;
}
}
讓我知道您是否需要更多信息,並感謝您的閱讀!
我認為您應該將比例尺的邊框加倍
for (CCSprite *sprite in movableSprites) {
if (CGRectContainsPoint(sprite.boundingBox*sprite.scale, touchLocation)) {
//touch sprite action
}
}
關於轉換點,如果我需要絕對的屏幕點,請始終使用:
convertToWorldSpace:CGPointZero.
我不太確定為什么您需要在觸摸位置上使用它,當我需要忽略它們在父節點中的位置時,通常會在精靈上執行此操作。
除此之外,如果您的游戲不是真正的多點觸控游戲,則最好使用ccTouchBegan而不是ccTouchesBegan。
使用此功能獲取精靈整流器。
-(CGRect)getSpriteRect:(CCNode *)inSprite
{
CGRect sprRect = CGRectMake(
inSprite.position.x - inSprite.contentSize.width*inSprite.anchorPoint.x,
inSprite.position.y - inSprite.contentSize.height*inSprite.anchorPoint.y,
inSprite.contentSize.width,
inSprite.contentSize.height
);
return sprRect;
}
- (void)ccTouchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
UITouch *myTouch = [touches anyObject];
CGPoint location = [myTouch locationInView:[myTouch view]];
location = [[CCDirector sharedDirector] convertToGL:location];
for (CCSprite *sprite in movableSprites)
{
CGRect rect = [self getSpriteRect:sprite];
if (CGRectContainsPoint(rect, location))
{
NSLog(@"Woohoo, you touched a sprite!");
break;
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.