Search code examples
iosxcodepositionsprite-kittouchesbegan

Sprite node won't move when touch is recognized in Sprite Kit


I am trying to make a sprite node move when the user touches above a certain point on the screen. My touch is being recognized, but no movement is happening!

-(id)initWithSize:(CGSize)size {    
if (self = [super initWithSize:size]) {
    /* Setup your scene here */

    self.backgroundColor = [SKColor colorWithRed:0.15 green:0.15 blue:0.3 alpha:1.0];
    self.anchorPoint = CGPointMake(0.5, 0.5);

    SKSpriteNode *_box = [SKSpriteNode spriteNodeWithColor:[SKColor redColor] size:CGSizeMake(50, 50)];
    _box.position = CGPointMake(0.5,0.5);

    [_box addChild:_box];
}
return self;
}

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
/* Called when a touch begins */

for (UITouch *touch in touches) {
    CGPoint location = [touch locationInNode:self];

    _currentTouch = touch;
}
}

-(void)update:(CFTimeInterval)currentTime {
/* Called before each frame is rendered */
CGPoint currentLocation = [_currentTouch locationInView:_currentTouch.view];
if (currentLocation.y > 300) {
    _box.position = CGPointMake(_box.position.x, _box.position.y + 20);
    NSLog(@"touching");
     }
}

@end

I'm not sure if I'm just going about it the wrong way, but I could desperately use some help! Thanks!


Solution

  • There are a number of mistakes in your code so it's easier to show you a sample project which does what you are asking:

    #import "MyScene.h"
    
    @implementation MyScene
    {
        SKSpriteNode *myNode;
    }
    
    -(id)initWithSize:(CGSize)size
    {
        if (self = [super initWithSize:size])
        {
            myNode = [SKSpriteNode spriteNodeWithColor:[SKColor redColor] size:CGSizeMake(30, 30)];
            myNode.position = CGPointMake(100, 100);
            [self addChild:myNode];
        }
        return self;
    }
    
    -(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
    {
        UITouch *touch = [touches anyObject];
        CGPoint touchLocation = [touch locationInNode:self.scene];
    
        if(touchLocation.y > 200)
        {
            myNode.position = CGPointMake(myNode.position.x, myNode.position.y+10);
        }
    }
    
    -(void)update:(CFTimeInterval)currentTime
    {
        //
    }
    
    @end