0
votes

Im using Spritekit to create a game for iOS 7. The game has circles moving across the screen using this code

_enemy = [SKSpriteNode spriteNodeWithImageNamed:@"greeny"];
        _enemy.position = CGPointMake(CGRectGetMidX(self.frame)+300,
                                      CGRectGetMidY(self.frame));
_enemy.size = CGSizeMake(70, 70);
_enemy.physicsBody = [SKPhysicsBody bodyWithCircleOfRadius:35];
_enemy.physicsBody.mass = 0;

_enemy.physicsBody.categoryBitMask = Collisiongreen;
[_enemies addObject:_enemy];
NSLog(@"Enemies%lu",(unsigned long)_enemies.count);

[self addChild:_enemy];
[_enemy runAction:[SKAction moveByX:-900 y:0 duration:4]];
[self runAction:[SKAction playSoundFileNamed:@"Spawn.wav" waitForCompletion:NO]];
[self runAction:[SKAction sequence:@[
                                  [SKAction waitForDuration:1.4],
                                  [SKAction performSelector:@selector(move)
                                                   onTarget:self],
                                     ]]];

I would like to have it that when the user touches one of the objects moving across the screen that they can move it with their finger either up or down (thats why I'm using touches moved) The code i have set up right now is

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

    if(_dead)
        return;
    UITouch *touch = [touches anyObject];
    CGPoint location = [touch locationInNode:self];

    if(CGRectContainsPoint(_enemy.frame, location)){

        [_enemy runAction:[SKAction moveTo:[[touches anyObject] locationInNode:self] duration:0.01]];
    }

My problem is that if i touch it the object will move a few pixels but will stop right after. How can I get it to move with my finger and if i let go it will continue moving left like programed before? Thanks!!

1

1 Answers

1
votes

So the trick here is that in the touchesMoved method, you want the enemy's postion set to the location of your touch. Use the touchesEnded method to execute a method that makes the enemy continue in the direction of your last touch. This is a rough non-tested example.

You need to store the difference of the current location with the previous location.

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

    if(_dead)
        return;
    UITouch *touch = [touches anyObject];
    CGPoint location = [touch locationInNode:self];

    if(CGRectContainsPoint(_enemy.frame, location)){

        someBool = False;
        [_enemy setPosition:location];
        changeInX = location.x - lastX;
        changeInY = location.y - lastY;
        lastX = location.x;
        lastY = location.y;
    }
}

- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
    someBool = True;
}

- (void)update:(NSTimeInterval)currentTime
{
...
    if (someBool) {
        enemy.position = CGPointMake((enemy.position.x + changeInX), (enemy.position.y + changeInY));
    }
...
}