Search code examples
iosobjective-c2d-games

Move object while user holding touch


I want to create simple app (clone of Road Fighter actually http://youtu.be/CDMcY3wLd1Q) where: rectangle UIView (car) moves left, if user press left side of screen and it moves right if user press right side.

I already figured out how to recognise touches (two ways: with "UILongPressGestureRecognizer" and with "touchesBegan:" function) but i don't understand how to create animation.

Pseudocode should looks like this (or maybe i'm wrong):

if user touch
    if touch.coordinate.x>160 then
        while holding
            UIView.coordinate.x += 0.01;
    if touch.coordinate.x<160 then
        while holding
            UIView.coordinate.x -= 0.01;

Solution

  • There's another function called -(void)touchesEnded so when touchbegan, you keep move the car to one direction and stop moving while touchesended was called. Simple solution is using a flag like bool carismovingleft call the loop moving function in touchbegin:

    - (void)touchesBegan... {
        //mark the flag
        self.carismovingleft = true;
        //start moving the car  
        [self movingcar];
    }
    
    - (void)movingcar {
        if (self.carismovingleft) {
            //move the car subview to left a little bit
            .......
            //now we keep moving a little bit till someone  stop it
            //call moving again after a delay 
            //otherwise the car will move all the way in one frame
            [self performSelector: @selector(movingcar) withObject:nil afterDelay:1];
        }
    }
    
    - (void)touchesEnded... {
        //stop flag
        self.carismovingleft = false;
    }
    

    It's just a basic concept of how to implement it, you need coding by yourself.