继承SKSpriteNode,重写touches逻辑,可实现类似COC游戏场景的平移和缩放。
代码如下:
- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
if (1 == touches.count) {
UITouch *touch = [touches anyObject];
CGPoint currentPoint = [touch locationInNode:self.parent];
CGPoint previousPoint = [touch previousLocationInNode:self.parent];
CGPoint translation = CGPointMake(currentPoint.x - previousPoint.x, currentPoint.y - previousPoint.y);
[self handlePanTranslation:translation];
} else if (2 == touches.count) {
NSArray *arr = [touches allObjects];
UITouch *touch1 = [arr objectAtIndex:0];
UITouch *touch2 = [arr objectAtIndex:1];
CGPoint position1 = [touch1 locationInNode:self];
CGPoint position2 = [touch2 locationInNode:self];
CGPoint previousPosition1 = [touch1 previousLocationInNode:self];
CGPoint previousPosition2 = [touch2 previousLocationInNode:self];
// calculate pinch rate and execute pinch
CGFloat distance = WLDistanceBetweenPoints(position1, position2);
CGFloat preDistance = WLDistanceBetweenPoints(previousPosition1, previousPosition2);
CGFloat rate = self.currentRate + (distance - preDistance) / preDistance;
CGFloat minWidth = self.scene.size.width;
CGFloat minHeight = self.scene.size.height;
CGFloat minWidthRate = minWidth / 1280.f;
CGFloat minHeightRate = minHeight / 656.f;
rate = MIN(rate, 1.5);
rate = MAX(rate, minWidthRate);
rate = MAX(rate, minHeightRate);
CGSize beforeSize = self.size;
self.xScale = rate;
self.yScale = rate;
CGSize afterSize = self.size;
self.currentRate = rate;
// garuntee edge from out of screen
CGFloat xDelta = (afterSize.width - beforeSize.width) / 2;
CGFloat yDelta = (afterSize.height - beforeSize.height) / 2;
CGPoint currentPosition = self.position;
currentPosition.x -= xDelta;
currentPosition.y -= yDelta;
currentPosition.x = MIN(currentPosition.x, 0);
currentPosition.x = MAX(currentPosition.x, self.scene.size.width - self.size.width);
currentPosition.y = MIN(currentPosition.y, 0);
currentPosition.y = MAX(currentPosition.y, self.scene.size.height - self.size.height);
self.position = currentPosition;
}
}