-1
CGRect rect4 = CGRectMake(rock.position.x, rock.position.y, rock.size.width, rock.size.height);
CGRect bulletRect = CGRectMake(bullet.position.x, bullet.position.y, bullet.size.width, bullet.size.height);
if (CGRectIntersectsRect(bulletRect, rect4)) {
    NSLog(@"hit Bullet");
    //[bullet removeFromParent];
}

即使 rect 4 不在子弹附近,它似乎也“击中子弹”。谢谢

4

1 回答 1

0

I don't know exactly how your shapes look like, but my guess is that their are only loosly symbolized by a rectangle.

-First check that your x and y rock and bullet positions are really their upper left corner coordinates, if not consider a translation of your bounding rectangle.

-To increase the precision of the bounding shape, without getting too complicated you could use a cloud of points that are situated on the boarder of the less rectangular of your object. Then you would use CGRectContainsPoint to check if the shapes intersect. You should position your points on the most prominent part of the polygon boarder. You could get their coordinate relatively to the rock.position.x and y coordinates.

For example: you know your rock's x and y. You can situate a point with something like: p1 = x+dx, y+dy.

enter image description here

Note that here, in the case where there is no intersection, a typical bounding box approach would have considered it an intersection.

So, in code:

CGPoint p1 = CGPointMake(rock.position.x+dx, rock.position.y+dy);
CGRect bulletRect = CGRectMake(bullet.position.x, bullet.position.y, bullet.size.width, bullet.size.height);
if (CGRectContainsPoint(bulletRect, p1)) {
    NSLog(@"hit Bullet");
}

Of course, the more points you have, the more precise it will be. Just loop over a point array and break if you have a true.

Another option, much more complicated and accurate, could be a graphic engine such as Box2D

Hope it helped.

F


EDIT


Dx and Dy are the differences between your known point (rock.position.x, rock.position.y) and the point to test (p1 here).

dx and dy

于 2014-01-29T12:37:20.330 回答