SpriteKit 实现 COC 游戏场景的平移和缩放

继承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;
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值