一、主要實現
今天spritekit實現創建玩家角色精靈(SKSpriteNode *), 增加角色精靈的手勢操作,這裡增加的手勢計算方法與objective-c中是不一樣的,因為objective-c使用的坐標系與spritekit使用的坐標系不是一樣的,後面還增加了精靈的碰撞檢查代碼。
二、SKSpriteNode手勢
SKSpriteNode類自帶5個手勢監測的方法,
// 手指按下的時候調用
1、-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
// 手指移動的時候調用
2、-(void)touchesMoved:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
// 手指抬起的時候調用
3、- (void)touchesEnded:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
取消(非正常離開屏幕,意外中斷事件)
4、-(void)touchesCancelled:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
3D Touch相關方法,當前觸摸對象估計的觸摸特性,返回值是UITouchPropertyie、
5、-(void)touchesEstimatedPropertiesUpdated:(NSSet *)touches
6、上面5個方法中用得最多的是 1、2、3,下面我們要操作的角色精靈也是用到這三個手勢,實現的思路→當用戶點擊屏幕時進入到1手勢,判斷點擊的坐標點是不是在角色精靈精靈上,如果是才能執行2手勢,代碼中用了一個int變量紀錄,如果點擊到了角色精靈int=1,int=1時2手勢才能執行,當用戶手抬起時,將會執行手勢3,說明手勢結束,結束後我們將int=1設置為=0。
二、 代碼
1.場景層初始化中增加創建角色精靈的代碼:SKSpriteNode *FirendPlane
UIImage *RolePlaneImage=[UIImage imageNamed:@"AttackPlane"]; SKTexture *RolePlaneImageTextture = [SKTexture textureWithImage:RolePlaneImage]; FirendPlane=[SKSpriteNode spriteNodeWithTexture:RolePlaneImageTextture size:CGSizeMake(DEVICE_Width*0.25, DEVICE_Width*0.25)]; FirendPlane.physicsBody = [SKPhysicsBody bodyWithRectangleOfSize:FirendPlane.size]; /*增加碰撞監測代碼*/ FirendPlane.physicsBody.categoryBitMask = SKRoleCategoryFoePlane; FirendPlane.zPosition=1; FirendPlane.position=CGPointMake(self.frame.size.width/2, 50 ); [self addChild:FirendPlane];
2.增加手勢
-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event { UITouch *touctObj = [touches anyObject]; CGPoint location=[touctObj locationInNode:self]; CGFloat CurrentTagAreaX=FirendPlane.position.x-FirendPlane.size.width/2; CGFloat CurrentTagAreaY=FirendPlane.position.y-FirendPlane.size.height/2; if (location.x>=CurrentTagAreaX &&location.x<=FirendPlane.position.x+(FirendPlane.size.width/2) && location.y>=CurrentTagAreaY &&location.y<=FirendPlane.position.y+(FirendPlane.size.height/2)) { IsOrNoTachMyPlane=1; } } - (void)touchesEnded:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event { IsOrNoTachMyPlane=0; } -(void)touchesMoved:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event { if (IsOrNoTachMyPlane>0) { UITouch *touctObj = [touches anyObject]; CGPoint location=[touctObj locationInNode:self]; if (location.x >= self.size.width - (FirendPlane.size.width / 2)) { location.x = self.size.width - (FirendPlane.size.width / 2); }else if (location.x <= (FirendPlane.size.width / 2)) { location.x = FirendPlane.position.x; } if (location.y >= self.size.height - (FirendPlane.size.height / 2)) { location.y = self.size.height - (FirendPlane.size.height / 2); }else if (location.y <= (FirendPlane.size.height / 2)) { location.y = FirendPlane.position.y; } SKAction *action = [SKAction moveTo:CGPointMake(location.x, location.y) duration:0]; [FirendPlane runAction:action]; }
二、 下載地址
http://download.csdn.net/detail/liaohang1987x/9610880