【问题标题】:SpriteKit PhysicsBody: Could not create physics bodySpriteKit PhysicsBody:无法创建物理体
【发布时间】:2014-08-30 07:10:00
【问题描述】:

我的游戏中有一个玩家,它有两种状态,飞行和下降。他们每个人都有一个图像:player_flying,player_falling 对应。我也在使用物理物体来检测碰撞。当我使用一种纹理时,它完全正常运行。但是当我尝试在不同的条件下使用不同的纹理时,它会在日志中显示一个错误。我正在尝试这样:

if (self.player.physicsBody.velocity.dy > 30) {
    self.player.texture = [SKTexture textureWithImageNamed:@"player_flying"];
    self.player.physicsBody = [SKPhysicsBody bodyWithTexture:self.player.texture
                                                        size:self.player.size];        
}
else
{
    self.player.texture = [SKTexture textureWithImageNamed:@"player_falling"];
    self.player.physicsBody = [SKPhysicsBody bodyWithTexture:self.player.texture
                                                        size:self.player.size];
}

错误是:

2014-08-30 12:55:47.515 kalabaska[1569:50535] PhysicsBody:无法创建物理实体。

【问题讨论】:

  • 检查两张图片是否都已加载,即self.player.texture不能为nil
  • 它不是nil,实际上它甚至在游戏中改变了纹理,但不改变物理体,它在屏幕上显示为静态图像。
  • 上面的代码是在update方法中实现的吗?
  • 是的,是在update方法中实现的。

标签: objective-c sprite-kit


【解决方案1】:

感谢 0x141E,我发现我的纹理周围有一些白色的东西,在我删除它之后,一切都开始工作了。现在我想知道如何在代表我的物理对象的纹理周围隐藏笔触。

【讨论】:

    【解决方案2】:

    您不应以更新速率(每秒最多 60 次)更改玩家的纹理和物理主体。您应该仅在需要时更改它们。以下是如何做到这一点的示例:

    if (self.player.physicsBody.velocity.dy > 30) {
        // Change texture/body only if not already flying
        if (!isFlying) {
            self.player.texture = [SKTexture textureWithImageNamed:@"player_flying"];
            self.player.physicsBody = [SKPhysicsBody bodyWithTexture:self.player.texture
                                                            size:self.player.size];
            isFlying = YES;
        }      
    }
    else
    {
        // Change texture/body only if not already falling
        if (isFlying) {
            self.player.texture = [SKTexture textureWithImageNamed:@"player_falling"];
            self.player.physicsBody = [SKPhysicsBody bodyWithTexture:self.player.texture
                                                            size:self.player.size];
            isFlying = NO;
       }
    }
    

    【讨论】:

    • 也许您的图像太复杂而无法用于创建物理体。你可以改用基于 CGPath 的物理体吗?
    • 有没有办法让它变得简单?还是创建 CGPath 的唯一方法是对纹理的点进行强制处理?
    【解决方案3】:

    检查图像是否有偏离主图像的杂散像素。这可能会导致“无法创建物理体”错误。

    干净的图像 图像不干净 - 请注意右下角的额外像素岛 通常,这个额外的像素岛可能是一个非常轻/低 alpha 的块,看起来与背景相似,或者真的很难发现。

    我对所有图像进行了循环测试,如下所示:

                        let t = SKTexture(imageNamed: filename)
                        let physics = SKPhysicsBody(texture: t, size: t.size())
                        if physics.area == 0.0 {
                            print("File \(filename) - failed")
                        }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多