触摸图像时移动精灵

时间:2013-12-05 11:54:37

标签: ios sprite-kit

我是iOS开发的新手,并会提供一些帮助。我只是在触摸图像时尝试在屏幕上移动图像。

我编写了以下代码,但是当通过触摸屏幕上的任何位置来运行图像时:

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    /* create spritenode and add rocket image */

    SKSpriteNode *sprite1 = [SKSpriteNode spriteNodeWithImageNamed:@"rocket.png"];    
    sprite1.position = CGPointMake(400,400);

    SKAction *liftoff = [SKAction moveByX:0 y:1000 duration: 2];
    [sprite1 runAction:liftoff];

    [self addChild:sprite1];
}

2 个答案:

答案 0 :(得分:0)

更改您的方法如下:

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
  UITouch *touch = [touches anyObject];
  if ([touch view] == ImageViewOfYourImage) {
    /* create spritenode and add rocket image */

    SKSpriteNode *sprite1 = [SKSpriteNode spriteNodeWithImageNamed:@"rocket.png"];
    sprite1.position = CGPointMake(400,400);

    SKAction *liftoff = [SKAction moveByX:0 y:1000 duration: 2];
    [sprite1 runAction:liftoff];

    [self addChild:sprite1];
  }
}

其中ImageViewOfYourImage引用您的视图,其中显示您的图片。或者您可以用来检查UITouch对象的其他属性。

答案 1 :(得分:0)

这对我现在有用。当用户在battleShip SKSpriteNode上向左或向右移动手指时,我移动Node 希望这会有所帮助。

#import "NewGame.h"

@implementation NewGame

-(id)initWithSize:(CGSize)size
{
    if (self == [super initWithSize:size])

   {
        self.backgroundColor = [SKColor blackColor];

        SKSpriteNode *battleShip = [SKSpriteNode spriteNodeWithImageNamed:@"Spaceship.png"];
        CGRect battleShipFrame = CGRectMake(10, 10, 100, 100);
        [battleShip setSize:battleShipFrame.size];
        battleShip.position = CGPointMake(CGRectGetMidX(self.frame), 50);

        [self addChild:battleShip];
        _ship = battleShip; //@property (nonatomic, strong) SKSpriteNode *ship; in header file
    }
    return self;
}

-(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
    CGPoint currentLocation = [[touches anyObject] locationInNode:self];
    CGPoint previousLocation = [[touches anyObject] previousLocationInNode:self];
    CGRect shipRect = _ship.frame;
    if (CGRectContainsPoint(shipRect, previousLocation))
    {
        CGPoint lvPosition = CGPointMake(_ship.position.x - (previousLocation.x - currentLocation.x), _ship.position.y);
        _ship.position = lvPosition; // works for me from Apple`s demo project

    //tried to use the under code - but it simpy moves spaceship away from screen)
    // so enden with simple setting the " position " property of SkSpriteNode
    // _ship   :

    //SKAction *moveNode = [SKAction moveByX:lvPosition.x y:0.0 duration:0.0];
    //[_ship runAction: moveNode];
    }
}