cocos2dです。タッチして表示したオブジェクトを動かすというコードを試している最中です。 2010/07/18
2010/07/19

cocos2dです。タッチして表示したオブジェクトを動かすというコードを試している最中です。
cocos2dはゲーム向けのフレームワークです。おそらく僕が生のcocoa touchを使ってコードを書いていくよりずいぶん楽ができるだろうと期待してます....


さて、画面に何やら表示するさいにはCCSpriteというのを使うようです。
で、それを画面でタッチして動かしたいわけなので、イベントをひろう方法は、えーと、
イベントをひろうのは下記
- (void)ccTouchesBegan:(NSSet *)touches withEvent:(UIEvent *)event;
- (void)ccTouchesMoved:(NSSet *)touches withEvent:(UIEvent *)event;
- (void)ccTouchesEnded:(NSSet *)touches withEvent:(UIEvent *)event;
- (void)ccTouchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event;


で、ccTouchesBeganで、タッチした位置がスプライトと重なっているか判定したい。


BOOL isOk = NO;
-(void)ccTouchesBegan:(NSSet*)touches withEvent:(UIEvent *)event
{

UITouch *touch =[touches anyObject];
CGPoint location =[touch locationInView:[touch view]];
location =[[CCDirector sharedDirector] convertToGL:location];
int offX = location.x;
int offY = location.y;

NSLog(@"%d %d", offX, offY);

CGRect スプライトRect = [self rectForSprite:スプライト];
if(CGRectContainsPoint(スプライトRect, location)) {
isOk = YES;
} else {
isOk = NO;
}
}


で、中で使われているrectForSpriteの実装は下記。
このメソッドは、Cocos2d: Trials and Tribulationsで紹介されていたものです。

-(CGRect)rectForSprite:(CCSprite *)sprite{

float h = [sprite contentSize].height;
float w = [sprite contentSize].width;
float x = sprite.position.x - w/2;
float y = sprite.position.y - h/2;

CGRect rect = CGRectMake(x,y,w,h);

return rect;
}


なんとかできてる気がするが...

: