Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sprite Kit - Move object to position of touch

I have an object in my scene. When I touch the screen I want the object's y position to become the y position of my touch. For that I have the following code:

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

    SKNode *player = [self childNodeWithName:@"player"];

    UITouch *touch = [touches anyObject];
    CGPoint positionInScene = [touch locationInNode:self];
    player.position = CGPointMake(player.position.x, positionInScene.y);
}

It works with this code, but how do I get the object to move to the touch y position at a steady speed? So, instead of jumping to the touch y position, move to it on a predefined speed.

like image 515
user2255273 Avatar asked Feb 12 '14 00:02

user2255273


1 Answers

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

    SKNode *player = [self childNodeWithName:@"player"];

    UITouch *touch = [touches anyObject];
    CGPoint positionInScene = [touch locationInNode:self];

  // Determine speed
int minDuration = 2.0;
int maxDuration = 4.0;
int rangeDuration = maxDuration - minDuration;
int actualDuration = (arc4random() % rangeDuration) + minDuration;

// Create the actions
SKAction * actionMove = [SKAction moveTo:CGPointMake(player.position.x, positionInScene.y); duration:actualDuration];
[player runAction:actionMove];

}
like image 81
Mika Avatar answered Oct 16 '22 20:10

Mika