Thanks Chris,
I got it working but your solution looked far more elegant so I did it your way and it works great. Many thanks for your help.
Below is the updated code just for the benefit of anyone else who may be trying to do something similar - hopefully save someone some time.
At the top of my dot-m file I have some constants defined.
#define kcaseBoundaryLeft 10
#define kcaseBoundaryBottom 10
#define kcaseBoundaryRight 400
#define kcaseBoundaryTop 280
then in the ccTouchMoved function I now have...
- (void)ccTouchMoved:(UITouch *)touch withEvent:(UIEvent *)event
{
NSAssert(state == kPackingItemStateGrabbed, @"PackinItem - Unexpected state!");
CGPoint touchPoint = [touch locationInView:[touch view]];
touchPoint = [[Director sharedDirector] convertCoordinate:touchPoint];
CGSize s = [self.texture contentSize];
float halfWidth = s.width / 2; // Half the width of the sprite
float halfHeight = s.height / 2; // Half the height of the sprite
int newX = touchPoint.x; // This stores our new x position
int newY = touchPoint.y; // This stores our new y position
NSLog(@"X:%f Y:%f",self.position.x, self.position.y);
// check to see if the touchPoint is to the left of the left boundary
if ((touchPoint.x - halfWidth) < kcaseBoundaryLeft) {
newX = kcaseBoundaryLeft + halfWidth;
// if it's not to left of the left boundary, check to see if it's to the right of the right boundary
} else if ((touchPoint.x + halfWidth) > kcaseBoundaryRight) {
newX = kcaseBoundaryRight - halfWidth;
//if it's not too far right or left, the just use the touchPosition
} else {
newX = touchPoint.x;
}
// check to see if the touchPoint is below the bottom boundary
if ((touchPoint.y - halfHeight) < kcaseBoundaryBottom) {
newY = kcaseBoundaryBottom + halfHeight;
// if it's not below the top boundary, check to see if it's above the top boundary
} else if ((touchPoint.y + halfHeight) > kcaseBoundaryTop) {
newY = kcaseBoundaryTop - halfHeight;
//if it's not too far above or below, then just use the touchPosition
} else {
newY = touchPoint.y;
}
self.position = CGPointMake(newX, newY);
}