給飛機添加一個拖動的手勢
1.創(chuàng)建一個手勢pan盈魁,添加與之關(guān)聯(lián)的動作panAction
2.添加手勢pan到view
-(void)didMoveToView:(SKView *)view {
self.size = self.view.frame.size;
[self backgroundNode];
[self planeNode];
//創(chuàng)建一個手勢與panAction關(guān)聯(lián)
UIPanGestureRecognizer *pan = [[UIPanGestureRecognizer alloc]initWithTarget:self action:@selector(panAction:)];
//添加手勢到view
[self.view addGestureRecognizer:pan];
}
一、首先判斷手指按下的是否是飛機
//這里需要設(shè)置一個全局變量
bool isPlane;
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
isPlane = NO;
//獲取手指按下的位置
UITouch *touch = [touches anyObject];
CGPoint position = [touch locationInNode:self];
//獲取當(dāng)前位置的精靈(如果有)
SKNode *node = [self nodeAtPoint:position];
//判斷當(dāng)前位置的精靈的name是否為plane
if ([node.name isEqualToString:@"plane"]) {
//全局變量isPlane設(shè)為YES;
isPlane = YES;
}
}
二缔逛、編寫手勢對應(yīng)的動作
-(void)panAction:(UIGestureRecognizer *)sender {
//判斷isPlane是否為YES
if (isPlane) {
//獲取plane精靈
SKSpriteNode *plane = (SKSpriteNode *)[self childNodeWithName:@"plane"];
//因為手勢是添加到view上面的备埃,獲取傳遞進來view上面的手指拖動的坐標(biāo)
CGPoint position = [sender locationInView:sender.view];
//view坐標(biāo)(原點是左上角)和SpriteKit坐標(biāo)(原點是左下角)之間的轉(zhuǎn)換,x軸相同褐奴,y軸為與屏幕的height的差值
position = CGPointMake(position.x, self.size.height -position.y);
//根據(jù)手指位置改變plane位置
plane.position = position;
}
}