通过拖动屏幕在Y轴上移动Sprite

时间:2013-11-07 01:55:18

标签: iphone sprite sprite-kit

如何让精灵套件中的精灵在y轴上上下移动(iPhone处于横向状态)。精灵必须保持设定的X值。这是在用户拖动它时完成的。

3 个答案:

答案 0 :(得分:3)

您需要实施 touchesMoved

从接收器的先前位置减去当前位置,您将获得移动精灵的金额。

<强>目标C

- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {
  UITouch *touch = [touches anyObject];
  CGPoint scenePosition = [touch locationInNode:self];
  CGPoint lastPosition = [touch previousLocationInNode:self];

  CGPoint translation = CGPointMake(0.0, scenePosition.y - lastPosition.y);
  yourSprite.position = CGPointMake(yourSprite.position.x, yourSprite.position.y + translation.y); 
}

Swift 2.2

override func touchesMoved(touches: Set<UITouch>, withEvent event: UIEvent?) {
  for touch in touches {
    let scenePosition = touch.locationInNode(self)
    let lastPosition = touch.previousLocationInNode(self)

    let translation = CGPoint(x: 0.0, y: scenePosition.y - lastPosition.y)
    yourSprite.position = CGPointMake(yourSprite.position.x, yourSprite.position.y + translation.y);
  }
}

祝你好运!!

答案 1 :(得分:1)

绝对定位的一个非常简单的解决方案:

-(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
    CGPoint touchLocation;
    for (UITouch *touch in touches) {
        touchLocation = [touch locationInNode:self];
    }
    CGPoint spriteLocation = yourSprite.position; 
    spriteLocation.y = touchLocation.y;
    yourSprite.position = spriteLocation;
}

答案 2 :(得分:1)

您可以使用SKAction类的这种方法: -

- (void)touchesMoved:(NSSet *)触及withEvent:(UIEvent *)事件
{

   [mySprite runAction:[SKAction moveToY:400 duration:0.2];

}

此SKAction方法创建一个垂直移动节点的动作。