保持移动的图像在帧宽和高度内弹跳

时间:2013-09-24 19:13:42

标签: ios objective-c

我试图找出如何将图像保持在框架宽度和高度内。现在它只是环绕。我最好还是想创造一种能够保持在框架内并在内部反弹的东西。

-(void) moveButterfly {
    bfly.center = CGPointMake(bfly.center.x + bfly_vx, bfly.center.y + bfly_vy);

    if(bfly.center.x > frameWidth)
    {
        bfly.center = CGPointMake(0, bfly.center.y + bfly_vy);
    }
    else if (bfly.center.x < 0)
    {
        bfly.center = CGPointMake(frameWidth, bfly.center.y + bfly_vy);
    }

    if(bfly.center.y > frameHeight)
    {
        bfly.center = CGPointMake(bfly.center.x + bfly_vx, 0);
    }
    else if (bfly.center.y < 0)
    {
        bfly.center = CGPointMake(bfly.center.x + bfly_vx, frameHeight);
    }
}

1 个答案:

答案 0 :(得分:0)

-(void)moveButterfly{
    static int dx = 1;
    static int dy = 1;
    if (bfly.frame.origin.x >= self.view.bounds.size.width - bfly.bounds.size.width) {
        dx = -dx;
    }
    if (bfly.frame.origin.y >= self.view.bounds.size.height - bfly.bounds.size.height) {
        dy = -dy;
    }
    if (bfly.frame.origin.x <= 0) {
        dx = -dx;
    }
    if (bfly.frame.origin.y <= 0) {
        dy = -dy;
    }
    CGPoint point = bfly.center;
    point.x += dx;
    point.y += dy;
    bfly.center = point;
}

继续使用NSTimer以您想要更新位置的速率调用此功能。这里dx和dy是蝴蝶移动的速度。