在屏幕上来回移动物体?

时间:2014-08-31 12:21:33

标签: ios objective-c xcode nstimer

我刚刚开始使用我的第一个Xcode项目,并且我尝试使用两个计时器创建一个在屏幕上来回移动的正方形,因为我最终想让它成为用户可以通过点击屏幕上的按钮来停止对象(这是一个正方形)。 但就目前而言,我已将方块移至屏幕右侧并向后移动,但不幸的是我无法将其停在屏幕的另一侧。

我现在的代码是:

- (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);
}

我的代码中唯一不起作用的部分是我的第二个if语句。我该如何解决这个问题?

1 个答案:

答案 0 :(得分:0)

这应该这样做。从if中移除第二个moveSquare1并将其放入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];
    }
}

如果您有任何疑问,请告诉我。