我正在使用 Sprite Kit 构建一款游戏,该游戏需要根据用户的触摸进行快速精确的移动。我需要检测用户是否触摸了 View 中的“玩家”,如果触摸了,当他们移动时,玩家 Sprite 需要相应地随着触摸移动。
我现在可以使用此功能,但是,它不是很精确......移动输入越多(无需抬起手指), Sprite 从触摸位置获得的偏移就越大。
这是我现在正在使用的代码。
-(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;
}
它会检测触摸位置,检查以确保您正在触摸玩家 Sprite ,如果是,那么当您移动时, Sprite 也会移动......但如果您正在吊索,它可以很快离开你的手指周围(因为玩这个游戏会导致玩家这样做)。
任何人都可以建议一种更准确的方法来实现此目的,即使在不抬起手指的情况下多次移动时,也可以将 Sprite 保持在用户的手指之下吗?
最佳答案
您必须记住 -(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
仅在移动手指写入时才会被调用(抱歉无法帮助克鲁索督察引用)。
实际上,用户可以非常快速地将他/她的手指从一个位置移动到下一个位置,一旦手指抬起,您的位置更新就会停止。
我建议您创建一个 CGPoint 属性,并让 -(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
将位置存储在 CGPoint 属性中。
然后在您的 -(void)update:(CFTimeInterval)currentTime
中添加实际将玩家移动到手指坐标的代码。这应该会让事情变得更加顺利。
关于ios - 触摸和移动 Sprite 跟踪效果不佳,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22921269/