Search code examples
iosobjective-ccocoa-touchuitouch

moving 2 objects at same time


In my current ios project, I have dedicated one side of the screen to one object and the other side of the screen to the other object and i have made it so that if you swipe your finger across one side of the screen on the designated object would move. However, I want to make it so that you can move both objects at the same time in different movement but i cannot figure out how to do so. Below is my current code.

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
    UITouch *touch = [[event allTouches] anyObject];
    CGPoint location = [touch locationInView:touch.view];

    if (location.x <= 270 ) {
        [Person setCenter:CGPointMake(location.x, Person.center.y)];

    }
    else  {
        [Person1 setCenter:CGPointMake(location.x, Person1.center.y)];
    }
}

- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {
    UITouch *touch = [[event allTouches] anyObject];
    CGPoint location = [touch locationInView:touch.view];

    if (location.x <= 270 ) {
        [Person setCenter:CGPointMake(location.x, Person.center.y)];
    }
    else  {
        [Person1 setCenter:CGPointMake(location.x, Person1.center.y)];
    }
}

Solution

  • you should start handling multiple touches that are delivered in the touches set - loop through all the UITouch objects and do your handling.

    Edit: here's your code:

    - (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
        for(UITouch *touch in [event allTouches]) {
            CGPoint location = [touch locationInView:touch.view];
    
            if (location.x <= 270 ) {
                [Person setCenter:CGPointMake(location.x, Person.center.y)];
            }
            else  {
                [Person1 setCenter:CGPointMake(location.x, Person1.center.y)];
            }
        }
    }
    
    - (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {
        for(UITouch *touch in [event allTouches]) {
            CGPoint location = [touch locationInView:touch.view];
    
            if (location.x <= 270 ) {
                [Person setCenter:CGPointMake(location.x, Person.center.y)];
            }
            else  {
                [Person1 setCenter:CGPointMake(location.x, Person1.center.y)];
            }
        }
    }