0
我寫了下面的程序,它必須做到以下幾點:當用戶觸摸移動精靈時,它必須從場景中移除。Cocos2d觸摸,一些錯誤
但是,當我運行我的代碼時,會發生以下情況:當我觸摸最高的精靈時,它會消失,而它的鄰居。我該如何解決它?
這是代碼。
UPD:我測試了這個代碼更小的* .png文件,並且一切工作正常。但是在更大的* .png文件(像200x200像素,iPhone模擬器一樣),我有一個bug:對象與其最近的鄰居touchEvent刪除。
定義
#import <Foundation/Foundation.h>
#import "cocos2d.h"
@interface GameplayLayer : CCLayer {
NSMutableArray *arrayOfSprites;
}
@end
#import "GameplayLayer.h"
@implementation GameplayLayer
-(id)init
{
self = [super init];
self.isTouchEnabled=YES;
arrayOfSprites=[[NSMutableArray alloc] init];
if (self != nil)
{
int j=100;
for (int i=0; i<=2; i++) {
[arrayOfSprites addObject:[CCSprite spriteWithFile:@"sv_anim_1-hd.png"]];
[[arrayOfSprites objectAtIndex:i] setPosition:CGPointMake(j,j)];
[self addChild:[arrayOfSprites objectAtIndex:i] z:0 tag:i];
j+=100;
}
[self startRunning];
}
return self;
}
-(void)startRunning
{
CGSize screenSize=[[CCDirector sharedDirector] winSize];
for (CCSprite * currentSprite in arrayOfSprites)
{
[currentSprite runAction:[CCMoveTo actionWithDuration:10 position:CGPointMake(screenSize.height,screenSize.width/2)]];
}
}
-(void) registerWithTouchDispatcher
{
[[CCTouchDispatcher sharedDispatcher] addTargetedDelegate:self priority:0
swallowsTouches:YES];
}
-(BOOL) ccTouchBegan:(UITouch *)touch withEvent:(UIEvent *)event {
return YES;
}
-(void) ccTouchEnded:(UITouch *)touch withEvent:(UIEvent *)event {
CGPoint locationOfTouch=[self convertTouchToNodeSpace: touch];
for (CCSprite *currentSprite in arrayOfSprites)
{
if (CGRectContainsPoint(currentSprite.boundingBox, locationOfTouch))
{
NSLog(@"Sprite was touched");
[self removeChild:currentSprite cleanup:YES];
}
}
}
@end
THX您的回覆,但它不能正常工作:還是一樣的錯誤發生。 – 2012-07-27 08:51:03
@Taras Murzenkov,嘿編輯你的問題,並添加GameplayLayer.h接口聲明,並顯示代碼,你初始化這個類 – Guru 2012-07-27 08:56:01
@Raj,CCSprites有一個boundingBox屬性。 '我的想法yourSprite.boundingBox'。 – tallen11 2012-07-27 18:44:43