当我尝试在b2Body
课程中使用NSObject
的功能时,我的应用会崩溃。
这是我班级的界面:
#import <Foundation/Foundation.h>
#import "Box2D.h"
#import "GLES-Render.h"
#import "cocos2d.h"
#import "HelloWorldScene.h"
@interface Magnet : NSObject {
b2Body* body;
}
@property (readwrite,assign) b2Body* body;
@end
以下是我在HelloWorldScene.h中声明它的方式:
#import "cocos2d.h"
#import "Box2D.h"
#import "GLES-Render.h"
#import <UIKit/UIKit.h>
#import "Magnet.h"
@class Magnet;
@interface HelloWorld : CCLayer {
b2World* world;
GLESDebugDraw *m_debugDraw;
Magnet *magnet;
}
以下是我在HelloWorldScene.mm中访问b2Body
中magnet
的方法:
b2BodyDef bodyDef2;
bodyDef2.type = b2_staticBody;
bodyDef2.position.Set(300/PTM_RATIO, 150/PTM_RATIO);
bodyDef2.userData = sprite2;
magnet.body = world->CreateBody(&bodyDef2);
// Define another box shape for our dynamic body.
//b2PolygonShape dynamicBox;
b2CircleShape dynamicBox2;
//dynamicBox.SetAsBox(1.0f, 1.0f);//These are mid points for our 1m box
dynamicBox2.m_radius = 0.49;
// Define the dynamic body fixture.
b2FixtureDef fixtureDef2;
fixtureDef2.shape = &dynamicBox2;
fixtureDef2.density = 1.3f;
fixtureDef2.friction = 1.0f;
magnet.body->CreateFixture(&fixtureDef2);
我的代码有问题吗?
我在CreateFixture()
函数的Box2D源文件中收到了SIGABRT。我该怎么办?
对于这个烂摊子感到抱歉,这是回溯:
(gdb) bt
#0 0x0002f35c in b2Body::CreateFixture (this=0x0, def=0xbfffd360) at b2Body.cpp:141
#1 0x00004f7e in -[HelloWorld loadLevel:] (self=0x5544770, _cmd=0xfbc7c, level=1) at HelloWorldScene.mm:255
#2 0x0000573d in -[HelloWorld init] (self=0x5544770, _cmd=0x4ffd774) at HelloWorldScene.mm:140
#3 0x0009d7b1 in +[CCNode node] (self=0x147100, _cmd=0xfc558) at CCNode.m:231
#4 0x0000377d in +[HelloWorld scene] (self=0x147100, _cmd=0xfb61c) at HelloWorldScene.mm:39
#5 0x000036d7 in -[MagnetSpillAppDelegate applicationDidFinishLaunching:] (self=0x680b9f0, _cmd=0xca40a3, application=0x5511370) at MagnetSpillAppDelegate.mm:96
#6 0x008b1ce2 in -[UIApplication _callInitializationDelegatesForURL:payload:suspended:] ()
#7 0x008b3d88 in -[UIApplication _runWithURL:payload:launchOrientation:statusBarStyle:statusBarHidden:] ()
#8 0x008be617 in -[UIApplication handleEvent:withNewEvent:] ()
#9 0x008b6abf in -[UIApplication sendEvent:] ()
#10 0x008bbf2e in _UIApplicationHandleEvent ()
#11 0x029ca992 in PurpleEventCallback ()
#12 0x0147d944 in __CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE1_PERFORM_FUNCTION__ ()
#13 0x013ddcf7 in __CFRunLoopDoSource1 ()
#14 0x013daf83 in __CFRunLoopRun ()
#15 0x013da840 in CFRunLoopRunSpecific ()
#16 0x013da761 in CFRunLoopRunInMode ()
#17 0x008b37d2 in -[UIApplication _run] ()
#18 0x008bfc93 in UIApplicationMain ()
#19 0x00002cc4 in main (argc=1, argv=0xbffff058) at main.m:13
答案 0 :(得分:1)
没有崩溃,很难具体说明出了什么问题。
然而,该代码充满了崩溃的可能性。
您正在使用堆栈中未分配的结构。如果在完成这些结构之前该代码的范围消失,则会导致崩溃和未定义的行为。
您没有初始化这些结构中的所有字段;其余值将处于未定义状态。由于无法区分未初始化的float32
和初始化的float32
,因此最终会导致问题。
您正在堆栈上设置引用堆栈上其他结构的结构;第一点的另一种形式,但是应该被调出来,因为它使指针泄漏到堆栈变得更加容易。
b2Body :: CreateFixture()的第141行是一个断言:
b2Assert(m_world->IsLocked() == false);
你的世界被锁定了吗?看起来不应该。