矩形和圆碰撞检测 [英] Rectangle and Circle collision detection

查看:192
本文介绍了矩形和圆碰撞检测的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在一个矩形和一个圆之间进行碰撞检测。我想出了这个方法:

   - (BOOL)isCollidingRect:(CCSprite *)spriteOne WithSphere:(CCSprite *)spriteTwo { 
float diff = ccpDistance(spriteOne.position,spriteTwo.position);
float obj1Radii = [spriteOne boundingBox] .size.width / 2;
float obj2Radii = [spriteTwo boundingBox] .size.width / 2;
if(diff< obj1Radii + obj2Radii){
return YES;
} else {
return NO;
}
}

这是我如何检查:

  if([self isCollidingRect:player WithSphere:blocker] == true){
[self playerdeathstart];
}

这似乎在矩形的一边正常工作,高于或低于它。在顶部和底部,碰撞发生得太早。





有没有办法得到这种碰撞检测正确?感谢您的帮助。

解决方案

您可以使用 CGRectIntersectsRect 实现此目的。



<$ c $ p> - (BOOL)isCollidingRect:(CCSprite *)spriteOne WithSphere:(CCSprite *)spriteTwo {
return CGRectIntersectsRect([spriteOne boundingBox],[spriteTwo boundingBox ]);
}

这不是像素完美,但是我知道在这种情况下不是必需的。


I am trying to do collision detection between a rectangle and a circle. I came up with this method:

-(BOOL) isCollidingRect:(CCSprite *) spriteOne WithSphere:(CCSprite *) spriteTwo {
    float diff = ccpDistance(spriteOne.position, spriteTwo.position);
    float obj1Radii = [spriteOne boundingBox].size.width/2;
    float obj2Radii = [spriteTwo boundingBox].size.width/2;
    if (diff < obj1Radii + obj2Radii) {
        return YES;
    } else {
        return NO;
    }
}

and this is how I check it:

if ([self isCollidingRect:player WithSphere:blocker] == true) {
   [self playerdeathstart];
}

This seems to work properly on the side of the rectangle but it doesn't above or below it. On the top and bottom, the collision occurs too early.

Is there a way I can get this collision to detected properly? Thank you for your help.

解决方案

You can use CGRectIntersectsRect to achieve this.

-(BOOL) isCollidingRect:(CCSprite *) spriteOne WithSphere:(CCSprite *) spriteTwo {
    return CGRectIntersectsRect([spriteOne boundingBox],[spriteTwo boundingBox]);
}

It is not pixel perfect but as i understand that is not necessary in this case.

这篇关于矩形和圆碰撞检测的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆