我是 Sprite Kit 的新手,我想知道如何让 Sprite 跟随触摸。例如,我的玩家 Sprite 位于屏幕底部。当我点击屏幕顶部时,玩家 Sprite 应该以一定的速度移动到触摸点 - 如果我移动手指,它应该始终指向触摸点。这就是我尝试实现它的方式:
-(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"];
}
}
但是,当移动手指时, Sprite 的移动非常迟缓。有什么办法可以让 Action 变得漂亮流畅吗?
任何帮助将不胜感激!
编辑:我想我已经找到了一个解决方案,我修改了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"];
}
}
}
最佳答案
我会在 touchesBegan
上将 UITouch
绑定(bind)到 Sprite,在 touchesEnded
上取消绑定(bind)。然后在每次更新时使用单极过滤器接近 UITouch
位置。
根本不需要任何操作,也不需要以这种方式实现 touchesMoved
。整个东西变得更加封装。
或者使用SKPhysicsJointSpring
。创建一个用于触摸的节点,然后创建一个连接 Sprite 和触摸节点的 Spring 关节。然后仅调整触摸节点位置。
Sprite
@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]; }
关于iOS Sprite 套件 : How to make Sprite follow Touches,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21597014/