给飞机添加一个拖动的手势
1.创建一个手势pan,添加与之关联的动作panAction
2.添加手势pan到view
-(void)didMoveToView:(SKView *)view {
self.size = self.view.frame.size;
[self backgroundNode];
[self planeNode];
//创建一个手势与panAction关联
UIPanGestureRecognizer *pan = [[UIPanGestureRecognizer alloc]initWithTarget:self action:@selector(panAction:)];
//添加手势到view
[self.view addGestureRecognizer:pan];
}
一、首先判断手指按下的是否是飞机
//这里需要设置一个全局变量
bool isPlane;
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
isPlane = NO;
//获取手指按下的位置
UITouch *touch = [touches anyObject];
CGPoint position = [touch locationInNode:self];
//获取当前位置的精灵(如果有)
SKNode *node = [self nodeAtPoint:position];
//判断当前位置的精灵的name是否为plane
if ([node.name isEqualToString:@"plane"]) {
//全局变量isPlane设为YES;
isPlane = YES;
}
}
二、编写手势对应的动作
-(void)panAction:(UIGestureRecognizer *)sender {
//判断isPlane是否为YES
if (isPlane) {
//获取plane精灵
SKSpriteNode *plane = (SKSpriteNode *)[self childNodeWithName:@"plane"];
//因为手势是添加到view上面的,获取传递进来view上面的手指拖动的坐标
CGPoint position = [sender locationInView:sender.view];
//view坐标(原点是左上角)和SpriteKit坐标(原点是左下角)之间的转换,x轴相同,y轴为与屏幕的height的差值
position = CGPointMake(position.x, self.size.height -position.y);
//根据手指位置改变plane位置
plane.position = position;
}
}