How to detect collision of sprite in cocos2d [closed]

半世苍凉 提交于 2019-12-13 12:52:08

问题


i want to detect collision of a sprite with another sprite. but i want to check whether the sprite is touched with left part of other sprite or touched with right part of sprite. i am using below code for detecting collision. but this detect the overall collision(sprite touched to at any point of other sprite). but want to count is as collision if the sprite is touched to front side of other sprite.

if (CGRectIntersectsRect(sprite1.boundingBox, sprite2.boundingBox)) {
            NSLog(@"sprite1 to delete");
 }

any one know how to do this?


回答1:


Would you be able to compare the positions of the sprites at the time of collision?

Assume sprite1.anchorpoint, sprite2.anchorpoint = ccp(0,0). At time when collision is detected:

// left part of sprite 1 touched right part of sprite 2
if (sprite1.position.x == sprite2.position.x + sprite2.contentSize.width.x) {

}
// right part of sprite 1 touched left part of sprite 2
else if (sprite1.position.x + sprite1.contentSize.width.x == sprite2.position.x) {

}



回答2:


By default in cocos2d the anchorpoint of a CCSprite is ccp(0.5, 0.5) which modifies the comparison of sprite positions. Comparing positions for the purpose to check relative distance between sprites in a gameloop, I think the equality operator is not the best choice, greater/less than equal is better to prepare different position situations, sprite moving steps.

To understand better I included the sprite situations for example:

To check the relative position (to detect a sprite is on what side of the other sprite) you have different choices to program in your collision detection check:

1)

if (CGRectIntersectsRect(sprite1.boundingBox, sprite2.boundingBox)) {
    CGPoint diff = ccpSub(sprite1.position, sprite2.position)
    if (diff.x<=0) {
       // sprite1 is on the left side
    } else {
       // sprite1 is on the right side
    }
}

2)

if (CGRectIntersectsRect(sprite1.boundingBox, sprite2.boundingBox)) {
    if (sprite1.position.x <= sprite2.position.x) {
       // sprite1 is on the left side
    } else {
       // sprite1 is on the right side
    }
}


来源:https://stackoverflow.com/questions/15873199/how-to-detect-collision-of-sprite-in-cocos2d

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!