【问题标题】:Collision detection does not return anything碰撞检测不返回任何东西
【发布时间】:2012-06-08 00:33:48
【问题描述】:

我在非常简单的碰撞检测方面遇到了一些麻烦。这是我目前正在使用的代码:

- (void) update:(ccTime)dt{
NSLog(@"update");
if (CGRectIntersectsRect([self.sprite boundingBox], [self.swat boundingBox])) {
    NSLog(@"detected");
}}

'sprite' 和 'swat' 是 CCSprite 的子类,它们被声明为属性,使用:

@property (nonatomic, assign) CCSprite *swat;
@property (nonatomic, assign) enemyClass *sprite; //enemyClass is a subclass of CCSprite
//note that they have also been synthesized

我是否需要更改属性才能使碰撞检测正常工作?

我也试过下面的代码:

这仅返回更新:

- (void) update:(ccTime)dt{
NSLog(@"update");
if (CGRectIntersectsRect(self.sprite.boundingBox, self.swat.boundingBox)) {
    NSLog(@"detected");
}}

这会一遍又一遍地返回“检测到”,即使它们没有发生碰撞:

- (void) update:(ccTime)dt{
NSLog(@"update");
if (CGRectIntersectsRect(self.sprite.textureRect, self.swat.textureRect)) {
    NSLog(@"detected");
}}

在两组代码中,都记录了“更新”,因此更新工作正常,只是 if 语句给我带来了问题。

如果您能给我任何解决方案来说明为什么这不起作用,或者任何其他方法让它起作用,我将不胜感激。谢谢。

【问题讨论】:

  • 是 self.sprite 还是 self.swat nil?您还应该对 boundingBoxes 进行 NSLog 记录,看看它们是否真的发生了碰撞。
  • @iBradApps sprite.boundingBox 记录 {{0,0},{0,0}} swat.boundingBox 记录 {{240,10},{0,0}} 第一组坐标似乎是他们开始的位置
  • 你是在更新方法中NSLogging吗?您自己应该看到它们正在通过 NSLogs 发生冲突。一旦你确认了,你就可以重构你的代码了。
  • @iBradApps 当我在更新方法中记录它时,我得到像 {{130,30}{0,0}} 这样的精灵,但特警总是返回 {{240,10} {0,0}},无论它在哪里。
  • 嗯,这很奇怪。我个人使用 Box2D 进行碰撞检测,因为就实际图像碰撞而言,它更容易且更准确。我建议你做 Box2D 碰撞。​​

标签: ios cocos2d-iphone collision-detection sprite cgrect


【解决方案1】:
如果第二个矩形在第一个 包含 中,

CGRectContainsRect 返回 true。您确定需要“包含”检查,而不是“相交”(CGRectIntersectsRect)检查吗?

【讨论】:

  • 没错,CGRectIntersectsRect 会更像我正在寻找的,但它仍然不起作用。
【解决方案2】:

尝试使用CGRectIntersectsRect()

【讨论】:

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