Sprite Kit - 将对象移动到触摸位置

5

我在场景中有一个物体。当我触摸屏幕时,我希望该物体的y位置变为我的触摸位置的y值。为此,我有以下代码:

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

    SKNode *player = [self childNodeWithName:@"player"];

    UITouch *touch = [touches anyObject];
    CGPoint positionInScene = [touch locationInNode:self];
    player.position = CGPointMake(player.position.x, positionInScene.y);
}

这段代码可以实现功能,但是如何让对象以稳定的速度移动到触摸的y位置?不是瞬间跳转到触摸y位置,而是以预定义的速度移动到该位置。

1个回答

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

    SKNode *player = [self childNodeWithName:@"player"];

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

  // Determine speed
int minDuration = 2.0;
int maxDuration = 4.0;
int rangeDuration = maxDuration - minDuration;
int actualDuration = (arc4random() % rangeDuration) + minDuration;

// Create the actions
SKAction * actionMove = [SKAction moveTo:CGPointMake(player.position.x, positionInScene.y); duration:actualDuration];
[player runAction:actionMove];

}

抱歉,但似乎这并没有起作用。我看不到任何变化。 - user2255273
1
非常感谢!我做了一个非常小的改动(请参见编辑),它起作用了。你是最棒的! - user2255273

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接