OGeek|极客世界-中国程序员成长平台

标题: ios - 触摸和移动 Sprite 不能很好地跟踪 [打印本页]

作者: 菜鸟教程小白    时间: 2022-12-12 09:14
标题: ios - 触摸和移动 Sprite 不能很好地跟踪

我正在使用 Sprite Kit 构建一个游戏,该游戏需要根据用户的触摸进行快速精确的 Action 。我需要检测用户是否触摸了 View 中的“玩家”,如果他们有,当他们移动时,玩家 Sprite 需要相应地随着触摸而移动。

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

这是我现在使用的代码。

-(void)touchesMovedNSSet *)touches withEventUIEvent *)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)touchesBeganNSSet*)touches withEventUIEvent*)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)touchesEndedNSSet*)touches withEventUIEvent*)event {
    self.isFingerOnPlayer = NO;
}

它会检测触摸位置,检查以确保您正在触摸玩家 Sprite ,如果您正在触摸,那么当您移动时, Sprite 也会...你的手指(因为玩这个游戏会导致玩家这样做)。

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



Best Answer-推荐答案


你必须记住 -(void)touchesMovedNSSet *)touches withEventUIEvent *)event 只有在移动的手指书写时才会被调用(抱歉不能帮助检查员克劳索引用)。

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

我建议您创建一个 CGPoint 属性并让 -(void)touchesMovedNSSet *)touches withEventUIEvent *)event 将位置存储在 CGPoint 属性中。 p>

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

关于ios - 触摸和移动 Sprite 不能很好地跟踪,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22921269/






欢迎光临 OGeek|极客世界-中国程序员成长平台 (http://ogeek.cn/) Powered by Discuz! X3.4