iOS Sprite Kit:如何让Sprite跟随Touches

我是Sprite Kit的新手,我想知道如何让一个精灵跟随触摸。 例如,我的玩家精灵在屏幕的底部。 当我点击屏幕顶部时,玩家精灵应该以一定的速度移动到触摸点 – 如果我移动手指,它应该始终指向触摸点。 这是我试图实现它的方式:

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event { for (UITouch *touch in touches) { CGPoint location = [touch locationInNode:self]; CGPoint diff = rwSub(location, self.player.position); CGPoint norm = rwNormalize(diff); SKAction *act = [SKAction moveByX:norm.x * 10 y:norm.y * 10 duration:0.1]; [self.player runAction:[SKAction repeatActionForever:act] withKey:@"move"]; } } - (void)touchesMoved:(NSSet*)touches withEvent:(UIEvent*)event { for (UITouch *touch in touches) { CGPoint location = [touch locationInNode:self]; CGPoint diff = rwSub(location, self.player.position); CGPoint norm = rwNormalize(diff); SKAction *act = [SKAction moveByX:norm.x * 10 y:norm.y * 10 duration:0.1]; [self.player runAction:[SKAction repeatActionForever:act] withKey:@"move"]; } } 

但是,移动手指时精灵移动非常缓慢。 有什么办法可以使运动更加美好和平滑?

任何帮助将不胜感激!

编辑:我想我已经find了一个解决scheme,我修改了touchesMoved函数:

 - (void)touchesMoved:(NSSet*)touches withEvent:(UIEvent*)event { for (UITouch *touch in touches) { [self.player removeActionForKey:@"move"]; CGPoint location = [touch locationInNode:self]; CGPoint diff = rwSub(location, self.player.position); CGPoint norm = rwNormalize(diff); [self.player setPosition: rwAdd(self.player.position, rwMult(norm, 2))]; SKAction *act = [SKAction moveByX:norm.x * 10 y:norm.y * 10 duration:0.01]; [self.player runAction:[SKAction repeatActionForever:act] withKey:@"move"]; } } } 

我将UITouch绑定到touchesBegan上的Sprite,在touchesEndedtouchesEnded 。 然后在每一个更新的方法,一个单极滤波器的UITouch位置。

根本不需要动作,也不需要执行动作就这样移动。 整个东西变得更加封装。


或者使用SKPhysicsJointSpring 。 为触摸创build一个节点,然后创build一个连接您的精灵和触摸节点的弹簧接点。 然后只调整触摸节点的位置。


雪碧

 @interface ApproachingSprite : SKSpriteNode @property (nonatomic, weak) UITouch *touch; @property (nonatomic) CGPoint targetPosition; -(void)update; @end @implementation ApproachingSprite -(void)update { // Update target position if any touch bound. if (self.touch) { self.targetPosition = [self.touch locationInNode:self.scene]; } // Approach. CGFloat filter = 0.1; // You can fiddle with speed values CGFloat inverseFilter = 1.0 - filter; self.position = (CGPoint){ self.targetPosition.x * filter + self.position.x * inverseFilter, self.targetPosition.y * filter + self.position.y * inverseFilter, }; } @end 

现场

 -(void)touchesBegan:(NSSet*)touches withEvent:(UIEvent*) event { self.sprite.touch = [touches anyObject]; } -(void)touchesEnded:(NSSet*)touches withEvent:(UIEvent*) event { self.sprite.touch = nil; } -(void)update:(CFTimeInterval) currentTime { [self.sprite update]; }