Young_Programmer
Young_Programmer

Reputation: 19

How to use touchAndHold event for sprite kit xcode 5

I'm trying to make a game with sprite kit and i need the character to move. I want the user to hold down the button for the character to move straight on the x axis. Right now you have to tap it multiple times for him to move.

Upvotes: 1

Views: 457

Answers (1)

meisenman
meisenman

Reputation: 1828

I would recommend setting a x direction velocity on the touchBegan event and on the touchUp event set the velocity to 0.

  1. Touch down on a Node (left or right)
  2. Check if direction node was touched
  3. Set speed based on which node was touched (+ value moves right, - value moves left)
  4. When Touch is released, reset velocity of character to 0

Here is some code I stripped from my game for you:

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

UITouch * touch = [touches anyObject];

CGPoint location = [touch locationInNode:self];



if([self.moveRightNode containsPoint: location]) {
     NSInteger xSpeed = yourSpeed;
     character.physicsBody.velocity = CGVectorMake(yourspeed, 0);
}
}

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

UITouch * touch = [touches anyObject];
CGPoint location = [touch locationInNode:self];
character.physicsBody.velocity = CGVectorMake(0, 0);

}

When setting the physicsworld up, make gravity 0 or make the character.physicsworld.dynamic=NO.

Upvotes: 1

Related Questions