Rectangle and Circle collision detection

前端 未结 2 460
礼貌的吻别
礼貌的吻别 2021-01-22 03:43

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

-(BOOL) isCollidingRect:(CCSprite *) spriteOne WithSphere:(CC         


        
相关标签:
2条回答
  • 2021-01-22 04:21

    This is not a solution for those who use Cocos2d-ObjC, but will help for Cocos2d-x devs (for instance, personally I found this topic because was searching for the same for my c++ game).

    Cocos2d-x has method "intersectsCircle" for Rect class.

    Here is how I solved in my c++ project almost the same problem as one described by you:

    bool ObstacleEntity::hasCollisionAgainst(cocos2d::Sprite *spr)
    {
        cocos2d::Rect rect = cocos2d::Rect( spr->getPositionX(), spr->getPositionY(), spr->getBoundingBox().size.width, spr->getBoundingBox().size.height);
    
        float rw = this->getBoundingBox().size.width / 2;
        float rh = this->getBoundingBox().size.height / 2;
    
        float radius = ( rw > rh ) ? rw : rh;
        cocos2d::Vec2 center( this->getPositionX() + rw, this->getPositionY() + rh );
    
        return rect.intersectsCircle( center, radius );
    }
    

    Passed Sprite here is rectangle, while ObstacleEntity always is almost ideally round. Note that anchor points for all entities are set to lower left corner in my case.

    0 讨论(0)
  • 2021-01-22 04:35

    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.

    0 讨论(0)
提交回复
热议问题