0

我正在关注斯坦福 ios7 课程,第 8 章,讲师在其中构建了一个简化的俄罗斯方块游戏,彩色块从上方掉落,您必须在其中填写行。在添加重力行为以使块下落之后,他添加了一个碰撞行为(注意下面的属性),懒惰地实例化它,并且在这样做的同时,他像这样设置边界

 _collider.translatesReferenceBoundsIntoBoundary = YES;

这使得块与屏幕底部发生碰撞(而不是掉落),因此它们可以相互堆叠。然后,他将碰撞行为添加到 animator 属性中,作为最后一步,在该drop方法中,他将 dropView(它们是块)添加到碰撞行为中。当他奔跑时,积木会撞到底部并相互堆叠。当我使用下面的代码运行时,块继续从屏幕底部(在模拟器上)落下。换句话说,没有堆叠。

你能明白为什么碰撞行为可能不起作用。

视图控制器

@property (strong,nonatomic) UIDynamicAnimator *animator;
@property (strong, nonatomic) UIGravityBehavior *gravity;
@property (strong, nonatomic) UICollisionBehavior *collider;

@end

@implementation DropItViewController

static const CGSize DROP_SIZE = { 40, 40 };
- (IBAction)tap:(UITapGestureRecognizer *)sender {

    [self drop];
}

- (UICollisionBehavior *)collider
{
    if (!_collider){
        _collider = [[UICollisionBehavior alloc] init];
        _collider.translatesReferenceBoundsIntoBoundary = YES;
        [self.animator addBehavior:_collider];
    }
    return _collider;
}

- (UIDynamicAnimator *)animator
{
    if (!_animator) {
        _animator = [[UIDynamicAnimator alloc] init];
    }
    return _animator;
}

-(UIGravityBehavior *)gravity
{
    if (!_gravity) {
        _gravity = [[UIGravityBehavior alloc] init];
        [self.animator addBehavior:_gravity];

    }
    return _gravity;
}

drop在方法中添加dropView到collider

-(void)drop
{
    CGRect frame;
    frame.origin = CGPointZero;
    frame.size = DROP_SIZE;
    int x = (arc4random() % (int)self.gameView.bounds.size.width) / DROP_SIZE.width;

    frame.origin.x = x * DROP_SIZE.width;
    UIView *dropView = [[UIView alloc] initWithFrame:frame];
    dropView.backgroundColor = self.randomColor;

    [self.gameView addSubview:dropView];

    [self.gravity addItem:dropView];
    [self.collider addItem:dropView];
}
4

2 回答 2

3

当你实例化你的UIDynamicAnimator,使用initWithReferenceView而不是init。然后当你使用时translatesReferenceBoundsIntoBoundary,它会知道使用什么引用边界。

于 2014-03-30T14:54:41.963 回答
1

我在同一门课程中,并认为我遇到了同样的问题。但是,请尝试在 4.0 英寸模拟器中运行。您的方块可能只是在屏幕外收集(在 3.5 英寸屏幕的范围之外)。

于 2014-05-27T22:00:35.273 回答