Search code examples
iosobjective-cxcodenstimer

Moving object back and forth on screen?


I'm just starting out with my first Xcode project and I'm trying to create a square that moves back and forth on the screen using two timers, because I eventually want to make it so that the user can stop the object (which is a square) by tapping a button on the screen. For now though, I've made the square move to the right side of the screen and move back, but unfortunately I cannot get it to stop at the other side of the screen.

My code right now is this:

- (void)viewDidLoad
{
    Square.center = CGPointMake(-9, 246);
    SquareTimer1 = [NSTimer scheduledTimerWithTimeInterval:0.004 target:self selector:@selector(moveSquare1)userInfo:nil repeats:YES];

   [super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
}

- (void)moveSquare1
{
    Square.center = CGPointMake(Square.center.x + 0.3, Square.center.y);

    if (Square.center.x > 290){
     [SquareTimer1 invalidate];
     SquareTimer1 = [NSTimer scheduledTimerWithTimeInterval:0.004 target:self selector:@selector(moveSquare2) userInfo:nil repeats:YES];
    }

    if (Square.center.x < -9){
        [SquareTimer1 invalidate];

        }
}

-(void) moveSquare2
{
    Square.center = CGPointMake(Square.center.x - 0.3, Square.center.y);
}

The only part of my code that is not working is my second if statement. How can I fix this?


Solution

  • This should do it. Remove that second if from moveSquare1 and place it in moveSquare2

    - (void)viewDidLoad
    {
        Square.center = CGPointMake(-9, 246);
        SquareTimer1 = [NSTimer scheduledTimerWithTimeInterval:0.004 target:self selector:@selector(moveSquare1)userInfo:nil repeats:YES];
    
        [super viewDidLoad];
        // Do any additional setup after loading the view, typically from a nib.
    }
    
    - (void)moveSquare1
    {
        Square.center = CGPointMake(Square.center.x + 0.3, Square.center.y);
    
        if (Square.center.x > 290){
            [SquareTimer1 invalidate];
            SquareTimer1 = [NSTimer scheduledTimerWithTimeInterval:0.004 target:self selector:@selector(moveSquare2) userInfo:nil repeats:YES];
        }
    }
    
    -(void) moveSquare2
    {
        Square.center = CGPointMake(Square.center.x - 0.3, Square.center.y);
    
        if (Square.center.x < -9){
            [SquareTimer1 invalidate];
    
            // If you want to move the Square back in the right side. Otherwise, comment this below line.
            SquareTimer1 = [NSTimer scheduledTimerWithTimeInterval:0.004 target:self selector:@selector(moveSquare1) userInfo:nil repeats:YES];
        }
    }
    

    Let me know if you have any doubts.