Search code examples
ioscharactertouchesbegan

Setting a limit within touchesbegan method


So I am using the touchesBegan method in my program in Xcode. When the user touches the screen, the character goes up the y axis, and when touches ended the user goes down. The problem I'm having is that the character is able to go off the screen (below 0 or above 768 [ipad] on the y axis).

How can I make it so that if the user touches the screen, and the character gets to y axis 0, the character will just stay there even if the user continues to touch. As well, if the user ends touch, how can I make sure the character doesn't go past 768.

I entered in a bunch of different if conditionals but the closest I got was to get the character to stay at 0 or 768, but when the user ended touch or began touch again, the character would just stay at 0 or 768. Any help??


Solution

  • In touchesBegan:

    //[animation begins]
    character.frame = CGRectMake(character.frame.origin.x, 0, character.frame.size.width, character.frame.size.height);
    //[animation ends]
    

    In touchesEnded:

    //[animation begins]
    character.frame = CGRectMake(character.frame.origin.x, (self.view.frame.size.height - character.frame.size.height), character.frame.size.width, character.frame.size.height);
    //[animation ends]