2011-03-08 36 views
2

我的代碼:移動與「ccTouchesMoved」的作品,但CCLayer它需要一些調整,我無法弄清楚

-(void) ccTouchesMoved:(NSSet *)touches withEvent:(UIEvent *)event 
{ 
    //Add a new body/atlas sprite at the touched location 
    for(UITouch *touch in touches) { 
     CGPoint touchLocation = [touch locationInView: [touch view]]; 
     CGPoint prevLocation = [touch previousLocationInView: [touch view]];  

     touchLocation = [[CCDirector sharedDirector] convertToGL: touchLocation]; 
     prevLocation = [[CCDirector sharedDirector] convertToGL: prevLocation]; 

     CGPoint diff = ccpSub(touchLocation,prevLocation); 

     [self setPosition: ccpAdd(self.position, diff)]; 
    } 

} 

此代碼讓我用我的手指移動圖層。這工作正常。但現在我想讓用戶只在預定義的CGRect中移動圖層。怎麼做?

例如:

CGRect rect = CGRectMake(0,0,600,320); 

現在玩家應該只允許這個矩形中移動層。在這個例子中,他只能將它(在iPod touch上)左右移動。 (直到600px)。

我需要改變以實現這個目標?

謝謝你的幫助。 祝你有美好的一天:)

回答

3

保持一個變量來檢查..例如..

distmoved = distmoved + touchlocation.x - prevlocation.x; 
if(distmoved<600) 
//move code 

注意distmoved是float ..

+0

+1我會試試這個 – cocos2dbeginner 2011-03-09 15:14:26

1

你應該自己檢查。這並不難,你的情況:

[self setPosition: ccpAdd(self.position, diff)]; 
if (self.position.x < minX) 
{ 
    //correct x position 
} 
if (...) 
// ... 
// ans so on 
+0

+ 1對於你的post..but我不知道誰更快......:/ – cocos2dbeginner 2011-03-12 19:40:55