cocos2dbeginner
cocos2dbeginner

Reputation: 2217

Moving CCLayer with "ccTouchesMoved" works but it needs some tweaks I can't figure it out

my code:

-(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)];
    }

}

This code lets me move the layer with my fingers. That works fine. But now I want to let the user only move the layer within a predefined CGRect. How to do that?

For example:

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

Now the player should be only allowed to move the layer within this rect. In that example he could only move it (on an ipod touch) to the left and right. (till 600px).

What do I need to change to achieve that?

Thank you for any help. Have a nice day :)

Upvotes: 2

Views: 2257

Answers (2)

xuanweng
xuanweng

Reputation: 1939

Keep a variable to check.. eg..

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

note that distmoved is a float..

Upvotes: 3

Andrew
Andrew

Reputation: 24866

You should make your own check. It's not hard in your case:

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

Upvotes: 1

Related Questions