2014-03-30 82 views
0

我跟随斯坦福ios7课程第8章,在那里教师建立一个简化的Tetris游戏,彩色块从上面落下,你必须填写行。加入重力行为,使块掉落后,他增加了一个碰撞行为(注意下面的属性),懒洋洋地实例化,并且在这样做,他将这样使块与屏幕边界碰撞

_collider.translatesReferenceBoundsIntoBoundary = YES; 

这使得该块与碰撞边界屏幕底部(而不是通过),以便它们可以堆叠在一起。然后他将碰撞行为添加到动画器属性中,并且作为最后一步,在drop方法中,他将dropView(它们是块)添加到碰撞行为中。当他跑步的时候,这些积木撞到了底部,并相互堆叠在一起。当我运行时,使用下面的代码,块继续在屏幕底部(在模拟器上)下降。换句话说,没有堆叠。

你能看出为什么碰撞行为可能不起作用。

的ViewController

@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; 
} 

的dropView添加对撞机在drop方法

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

回答

3

当你实例化你的UIDynamicAnimator,使用initWithReferenceView代替init。那么当你使用translatesReferenceBoundsIntoBoundary时,它会知道使用什么参考边界。

1

我在相同的课程,并认为我看到了同样的问题。但是,请尝试在4.0英寸模拟器中运行。您的广场可能只是在屏幕外收集(超出3.5英寸屏幕的界限)。