Cocos2d实现类似Clash of clans的缩放拖拽效果
最近开始跳入做游戏的坑了,而且想做一款独立游戏,虽然随时有烂尾的危险,但无妨一试~敬请期待~
目前正在准备游戏的原型,由于需要设计像COC的缩放场景,作为cocos2d的菜鸟兼ios开发新手,实在search遍了也没有像样的cocos2d代码,即使有效果也未如人意。stackoverflow上有老外关于pinch缩放手势的例子,但放到cocos2d环境,需要控制一个sprite或者tilemap的边界,就变得有点复杂了。这个问题实在卡了我好久好久,但通过参考了一些pinch示例以及不断调试anchor point和map position等值,最终解决,实在泪牛满面!
这个例子我使用了tilemap作为缩放的对象,当然需要的话也可以用sprite或其他代替。在使用了cocos2d的模版生成文件后,可以在hellolayer中的构造器里先添加本次需要的变量
-(void)adjustViewBoundingPosition:(CGPoint)newPos{ CGFloat adjustWidth=map.boundingBox.size.width*map.anchorPoint.x-map.position.x; CGFloat adjustHeight=map.boundingBox.size.height*map.anchorPoint.y-map.position.y; newPos.x= MIN(newPos.x, adjustWidth); newPos.x = MAX(newPos.x, winSize.width-[map boundingBox].size.width+adjustWidth); newPos.y = MIN(newPos.y,adjustHeight); newPos.y = MAX(newPos.y, winSize.height-[map boundingBox].size.height+adjustHeight); self.position=newPos;}-(BOOL) ccTouchBegan:(UITouch *)touch withEvent:(UIEvent *)event{return YES;}-(void)ccTouchMoved:(UITouch *)touch withEvent:(UIEvent *)event{ CGPoint touchLocation = [self convertTouchToNodeSpace:touch]; CGPoint oldTouchLocation = [touch previousLocationInView:touch.view]; oldTouchLocation = [[CCDirector sharedDirector] convertToGL:oldTouchLocation]; oldTouchLocation = [self convertToNodeSpace:oldTouchLocation]; CGPoint translation = ccpSub(touchLocation, oldTouchLocation); CGPoint newPos= ccpAdd(self.position, translation); [self adjustViewBoundingPosition:newPos];}