【问题标题】:Problem with the counter of collisions碰撞计数器的问题
【发布时间】:2011-07-23 11:13:09
【问题描述】:

这是我的代码:

-(void)detectCollision{

  imageView.center = CGPointMake(imageView.center.x + X, imageView.center.y + Y);


    if(CGRectIntersectsRect(imageView.frame,centre.frame)){


    label.text= [NSString stringWithFormat:@"%d", count];
  ++count;
}

我在detectCollision 上有一个CADisplayLink(60fps)。 每次“imageView”与“中心”发生碰撞时,我想增加一个“计数”,但我的问题是计数增加太快,每次发生碰撞时它都会增加接近 100 或 200,我不知道为什么.我该如何解决这个问题?

【问题讨论】:

    标签: iphone xcode uiimageview collision-detection counter


    【解决方案1】:

    这是因为每次框架开始相交时,

    if(CGRectIntersectsRect(imageView.frame,centre.frame))
    

    在帧分开并且 CADisplayLink 中的计数增加超过 100 之前,您的条件将成立

    因此您可以使用 BOOL 并在框架首次相交时将其设置为 true。然后检查它们是否分开并将 BOOL 设置为 false。

    在 init 中将 BOOL intersectFlag 初始化为 false。我假设框架最初不会相交。

    -(void)detectCollision
    { 
        imageView.center = CGPointMake(imageView.center.x + X, imageView.center.y + Y);
    
        if(!intersectFlag)
        {    
            if(CGRectIntersectsRect(imageView.frame,centre.frame))    
            {
                intersectFlag = YES;         
                label.text= [NSString stringWithFormat:@"%d", count];
                ++count;
            }
        }
        else
        {
            if(!CGRectIntersectsRect(imageView.frame,centre.frame))
            {
                intersectFlag = NO;
            }
        }
    }
    

    【讨论】:

    • 不,它不起作用,计数器增加得非常快,直到 imageView 不触及中心
    • 你是否在 init 中将 intersectFlag 初始化为 NO
    • 不,但我从不使用 BOOL,如何在 init 中将 intersectFlag 初始化为 NO
    • 声明 BOOL intersectFlag;在 *.h 文件中。并初始化 intersectFlag = NO;在 viewDidLoad
    【解决方案2】:

    要找出碰撞,你应该使用边界而不是框架

    bounds - 对象内部的大小

    frame - 从 superview x,y + size(bounds) 的偏移量

    这里我假设你处于纵向模式

    -(void)detectCollision{
    
            if(CGRectContainsPoint( imageView.bounds, CGPointMake(160, 240)) ){
    
    
                    label.text= [NSString stringWithFormat:@"%d", count];
    
                    ++count;
    
            }
    
    
        }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-09-28
      • 1970-01-01
      • 2011-05-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多