Cocos2d-iPhone 与 Box2D:CCPhysicsSprite EXC_BAD_ACCESS
问题描述
我最近才开始搞乱 cocos2d 的 Box2D 集成,虽然大部分过程都很简单直接,但在使用 CCPhysicsSprite(将 b2body 与 sprite 集成的 CCSprite 子类)时,我一直遇到 EXC_BAD_ACCESS 错误.我使用的代码是:
I just recently started messing with cocos2d's Box2D integration, while most of the process has been simple and straight forward, I keep running into a EXC_BAD_ACCESS error when using a CCPhysicsSprite (CCSprite subclass that integrates a b2body with the sprite). The code I'm using is:
此代码触发 EXC_BAD_ACCESS,我知道它是 CCPhysicsSprite,因为将 CCPhysicsSprite 更改为 CCSprite 会引发零错误:
This code triggers an EXC_BAD_ACCESS, I know it's the CCPhysicsSprite because changing CCPhysicsSprite to CCSprite throws zero errors:
我环顾四周,找不到真正的答案(因为所有示例代码都以这种方式使用 CCPhysicsSprite 没有错误).我确定我犯了一个愚蠢的错误,但我想在学习新东西时这是可以预料的:P
I've been looking around and can't find a real answer (as all the sample code uses CCPhysicsSprite in this way without error). I'm sure I'm making a stupid mistake but I guess that's to be expected when learning something new :P
提前致谢!
推荐答案
使用 CCPhysicsSprite
必须在设置精灵位置之前设置主体.我假设这条线是发生崩溃的地方:
With CCPhysicsSprite
you must set the body BEFORE you set the position of the sprite.
I assume that this line is where the crash occurs:
如果您查看 CCPhysicsSprite
,它会覆盖 position/setPosition 以始终使用包含的 b2body
对象中的值.所以它真的访问了它的 b2body 属性,在那个时候是 nil
→ Crash.通常,在创建 CCPhysicsSprite 后,您希望尽快设置其 .b2body - 可能会出现更多类似问题,因为您需要先设置 .b2body 属性.
If you look at CCPhysicsSprite
it overrides the position/setPosition to always use the values from the contained b2body
object. So it really accesses its b2body property, which is nil
at that point → Crash.
Generally after creating a CCPhysicsSprite you want to set its .b2body as soon as possible - there might be more occasions where similar problems might occur just because you need to set the .b2body property first.
所以,将 sprite.position = point;
移到 sprite.b2Body = body;
下方.
So, move sprite.position = point;
below sprite.b2Body = body;
.
这篇关于Cocos2d-iPhone 与 Box2D:CCPhysicsSprite EXC_BAD_ACCESS的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!