菜鸟教程小白 发表于 2022-12-12 09:14:44

ios - 触摸和移动 Sprite 不能很好地跟踪


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

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

<p>这是我现在使用的代码。</p>

<pre><code>-(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event{


    if (self.isFingerOnPlayer) {
      UITouch* touch = ;
      CGPoint touchLocation = ;
      CGPoint previousLocation = ;


      // 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 = ;
    CGPoint touchLocation = ;

    SKPhysicsBody* body = ;
    if (body &amp;&amp; ) {
      NSLog(@&#34;Began touch on player&#34;);
      self.isFingerOnPlayer = YES;

    }
}

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

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

<p>任何人都可以提出一种更准确的方法来实现这一点,即使在不抬起手指的情况下移动很多时也可以将 Sprite 保持在用户的手指下?</p></p>
                                    <br><hr><h1><strong>Best Answer-推荐答案</ strong></h1><br>
                                            <p><p>你必须记住 <code>-(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event</code> 只有在移动的手指书写时才会被调用(抱歉不能帮助检查员克劳索引用)。 </p>

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

<p>我建议您创建一个 CGPoint 属性并让 <code>-(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event</code> 将位置存储在 CGPoint 属性中。</code> p>

<p>然后在您的 <code>-(void)update:(CFTimeInterval)currentTime</code> 中添加实际将玩家移动到手指坐标的代码。这应该会让事情变得更顺利。</p></p>
                                   
                                                <p style="font-size: 20px;">关于ios - 触摸和移动 Sprite 不能很好地跟踪,我们在Stack Overflow上找到一个类似的问题:
                                                        <a href="https://stackoverflow.com/questions/22921269/" rel="noreferrer noopener nofollow" style="color: red;">
                                                                https://stackoverflow.com/questions/22921269/
                                                        </a>
                                                </p>
                                       
页: [1]
查看完整版本: ios - 触摸和移动 Sprite 不能很好地跟踪