触摸和移动精灵不能很好地跟踪

时间:2014-04-07 19:25:03

标签: ios touch sprite-kit

我正在使用Sprite Kit构建游戏,需要在用户触摸后快速精确移动。我需要检测用户是否触摸了视图中的“播放器”,如果有,则在移动时,播放器精灵需要相应地移动。

我现在有这个工作,但是,它不是很精确......运动输入越多(不抬手指),精灵从触摸位置得到的偏移就越多。

这是我现在正在使用的代码。

-(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event{


    if (self.isFingerOnPlayer) {
        UITouch* touch = [touches anyObject];
        CGPoint touchLocation = [touch locationInNode:self];
        CGPoint previousLocation = [touch previousLocationInNode:self];


        // Calculate new position for player
        int playerX = player.position.x + (touchLocation.x - previousLocation.x);
        int playerY = player.position.y + (touchLocation.y - previousLocation.y);

        // Limit x and y so that the player will not leave the screen any
        playerX = MAX(playerX, player.size.width/2);
        playerX = MIN(playerX, self.size.width - player.size.width/2);
        playerY = MAX(playerY, (player.size.width/2)-3+inBoundsOffset);
        playerY = MIN(playerY, (self.size.height - ((player.size.width/2)-3) - inBoundsOffset));


        // Update position of player
        player.position = CGPointMake(playerX, playerY);


    }


}

-(void)touchesBegan:(NSSet*)touches withEvent:(UIEvent*)event {

    UITouch* touch = [touches anyObject];
    CGPoint touchLocation = [touch locationInNode:self];

    SKPhysicsBody* body = [self.physicsWorld bodyAtPoint:touchLocation];
    if (body && [body.node.name isEqualToString: @"player"]) {
        NSLog(@"Began touch on player");
        self.isFingerOnPlayer = YES;

    }
}

-(void)touchesEnded:(NSSet*)touches withEvent:(UIEvent*)event {
    self.isFingerOnPlayer = NO;
}

它检测到触摸位置,检查以确保你正在触摸玩家精灵,如果你是,那么当你移动时,精灵也是如此......但如果你正在吊索它会很快下来你的手指(因为玩这个游戏会让玩家做)。

任何人都可以建议一种更准确的方法来实现这一点,即使在不抬手的情况下移动很多时,也会将精灵保持在用户的手指下吗?

1 个答案:

答案 0 :(得分:2)

你必须记住,-(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event仅在移动手指写入时被呼叫(抱歉无法帮助Inspector Clouseau参考)。

实际上,用户可以非常快速地将他/她的手指从一个位置移动到下一个位置,一旦手指抬起,您的位置更新就会停止。

我建议你做的是创建一个CGPoint属性并让-(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event将位置存储在CGPoint属性中。

然后在你的-(void)update:(CFTimeInterval)currentTime中添加实际将玩家移动到手指坐标的代码。这应该会让事情变得更顺畅。