简体   繁体   中英

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). The sprite has to stay on a set X value. This is done when the user drags it.

You need to implement touchesMoved

Subtract the the current location from previous location of the receiver and you will get the amount to move your sprite.

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

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:-

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

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

}

This SKAction Method creates an action that moves a node vertically.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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