0

这是我的代码:

    // setting background
_ground = [[SKSpriteNode alloc]
                         initWithColor:[SKColor greenColor]
                                  size:CGSizeMake([Helpers landscapeScreenSize].width, 50)];
_ground.name = @"ground";
_ground.zPosition = 1;
_ground.anchorPoint = CGPointMake(0, 0);
_ground.position = CGPointMake(0, 0);
_ground.physicsBody = [SKPhysicsBody bodyWithRectangleOfSize:CGSizeMake([Helpers landscapeScreenSize].width, 50)];
_ground.physicsBody.dynamic = NO;
_ground.physicsBody.affectedByGravity = NO;
_ground.physicsBody.categoryBitMask = groundCategory;
_ground.physicsBody.collisionBitMask = elementCategory;
_ground.physicsBody.contactTestBitMask = elementCategory;

绿色矩形定位没问题,但 SKPhysicsBody 没有正确表示这个矩形。看起来 SKPhysicsBody 没有根据精灵位置和锚点“移动”它的身体。SKPhysicsBody 向左移动 _ground.width 点。

我究竟做错了什么?

PS。更改为这个(代码)解决了我的问题,但我真的不喜欢这个解决方案,这似乎是一种丑陋的定位元素的方式。

_ground.position = CGPointMake([Helpers landscapeScreenSize].width / 2, 0);

+删除:

_ground.position = CGPointMake(0, 0);
4

1 回答 1

1

我昨天遇到了完全相同的问题;)对我来说,我通过使用 SpriteKit 的默认精灵定位解决了这个问题。我只是设置位置并将锚点保留为默认值。然后将物理体设置为精灵的大小。

将您的代码更改为以下内容并检查它是否有效:

_ground = [[SKSpriteNode alloc]
                         initWithColor:[SKColor greenColor]
                                  size:CGSizeMake([Helpers landscapeScreenSize].width, 50)];
_ground.position = CGPointMake([Helpers landscapeScreenSize].width / 2, 0);
_ground.physicsBody = [SKPhysicsBody bodyWithRectangleOfSize:_ground.size];

如果你仍然没有运气,你也可以尝试为你的精灵使用另一个初始化(这在我的项目中有效)。尝试使用纹理:

[[SKSpriteNode alloc] initWithTexture:[SKTexture textureWithCGImage:[UIImage imageWithColor:[UIColor whiteColor]].CGImage] color:[UIColor whiteColor] size:CGSizeMake(PLAYER_WIDTH, PLAYER_HEIGHT)];

不要忘记实现 (UIImage*)imageWithColor: 方法来为您创建所需颜色的 1x1 像素图像(请参见此处)。

于 2014-03-01T20:12:37.983 回答