I’m trying to make my sprites stay in screen borders using the following code:
- (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; } }
I understand that I need to add some code to specify borders. Something like the following:
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;}
But I’m new to objective C and I do not fully understand how to deal with it yet.
got it!
just add in
if (selSprite) {}this part of code