2012-01-17 64 views
0

我試圖讓我的精靈留在使用下面的代碼屏幕邊框:邊框拖動

- (BOOL)ccTouchBegan:(UITouch *)touch withEvent:(UIEvent *)event { 
CGPoint touchLocation = [self convertTouchToNodeSpace:touch]; 
[self selectSpriteForTouch:touchLocation]; 
return TRUE; } 

- (void)ccTouchMoved:(UITouch *)touch withEvent:(UIEvent *)event {  

CGPoint touchLocation = [self convertTouchToNodeSpace:touch]; 
if (selSprite) { 
CGPoint oldLocation = [touch previousLocationInView:touch.view]; 
oldLocation = [[CCDirector sharedDirector] convertToGL:oldLocation]; 
oldLocation = [self convertToNodeSpace:oldLocation]; 

CGPoint translation = ccpSub(touchLocation, oldLocation);  
CGPoint newPos = ccpAdd(selSprite.position, translation); 
selSprite.position = newPos;  } } 

我明白,我需要添加一些代碼到指定邊界。像下面這樣:

int width=point.x; 
    int height=point.y; 
    if (winSize.width-sprite.contentSize.width/2<width) { 
     width=winSize.width-sprite.contentSize.width/2;} 
    if (winSize.height-sprite.contentSize.height/2<height) { 
     height=winSize.height-sprite.contentSize.height/2;} 
    if (sprite.contentSize.height/2>height) { 
     height=sprite.contentSize.height/2;}              
    if (sprite.contentSize.width/2>width) { 
     width=sprite.contentSize.width/2;} 

但我是新來的objective C,我不完全瞭解如何尚未處理。

+0

好的!我已經做到了! – OnOff 2012-01-18 18:29:22

回答

0

明白了! 只需在if (selSprite) {}後添加代碼

int width=touchLocation.x; 
    int height=touchLocation.y; 
    if (selSprite.contentSize.width!=width) { 
     width=selSprite.contentSize.width/2;} 
    if (selSprite.contentSize.height/2<height) { 
     height=selSprite.contentSize.height/2;} 
    [selSprite setPosition:ccp(width,height)];