简体   繁体   English

通过拖动屏幕在Y轴上移动精灵

[英]Move Sprite on Y-axis by dragging screen

How do I make a sprite in sprite kit move up and down on the y axis (iPhone is in landscape). 如何在Sprite Kit中使Sprite在y轴上上下移动(iPhone处于横向)。 The sprite has to stay on a set X value. 子画面必须保持在设定的X值上。 This is done when the user drags it. 当用户拖动它时完成。

You need to implement touchesMoved 您需要实现touchesMoved

Subtract the the current location from previous location of the receiver and you will get the amount to move your sprite. 从接收器的先前位置减去当前位置,您将获得移动精灵的数量。

Objective-C Objective-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 斯威夫特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);
  }
}

Good Luck!! 祝好运!!

A very simple solution for absolute positioning: 绝对定位的非常简单的解决方案:

-(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;
}

You Can use this method of SKAction class:- 您可以使用SKAction类的此方法:-

-(void) touchesMoved:(NSSet *)touches withEvent:(UIEvent *) event -(void)touchesMoved:(NSSet *)触摸withEvent:(UIEvent *)事件
{ {

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

} }

This SKAction Method creates an action that moves a node vertically. 该SKAction方法创建一个垂直移动节点的动作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM