刚刚开始学习,想做一个小球可以在屏幕中央来回弹跳的游戏,但是遇到了如下问题。
// on "init" you need to initialize your instancebool HelloWorld::init()
{////////////////////////////// // 1. super init first if ( !Layer::init() ) { return false; } size = Director::getInstance()->getVisibleSize(); world = new b2World(b2Vec2(0, -10.0f)); addBall(); addEdge(); scheduleUpdate(); return true;}
void HelloWorld::update(float dt){
world->Step(dt, 8, 3); for(b2Body *b = world->GetBodyList(); b; b=b->GetNext()){ if(b->GetUserData() == sBall){ sBall->setPosition(b->GetPosition().x*RATIO, b->GetPosition().y*RATIO); printf("x=%f, y=%fn", b->GetPosition().x, b->GetPosition().y); } } return;}
void HelloWorld::addEdge(){
b2BodyDef def; def.position.SetZero(); edgeBody = world->CreateBody(&def); float widthInMeters = size.width / RATIO; float heightInMeters = size.height / RATIO; printf("widthInMeters=%f, heightInMeters=%fn", widthInMeters, heightInMeters); b2Vec2 lowerLeftCorner = b2Vec2(0, 0); b2Vec2 lowerRightCorner = b2Vec2(widthInMeters, 0); b2Vec2 upperLeftCorner = b2Vec2(0, heightInMeters); b2Vec2 upperRightCorner = b2Vec2(widthInMeters, heightInMeters); b2EdgeShape edge; //edge.Set(b2Vec2(0, 0), b2Vec2(size.width/RATIO, 0)); edge.Set(lowerLeftCorner, lowerRightCorner); edgeBody->CreateFixture(&edge, 0); edge.Set(lowerRightCorner, upperRightCorner); edgeBody->CreateFixture(&edge, 0); edge.Set(upperRightCorner, upperLeftCorner); edgeBody->CreateFixture(&edge, 0); edge.Set(upperLeftCorner, lowerLeftCorner); edgeBody->CreateFixture(&edge, 0); return;}
void HelloWorld::addBall(){
sBall = Sprite::create("180px-Basketball.png"); addChild(sBall); b2BodyDef b2Body; b2Body.position = b2Vec2(5, 5); b2Body.type = b2_dynamicBody; b2Body.userData = sBall; ball = world->CreateBody(&b2Body); b2CircleShape circle; circle.m_radius = 26.0; b2FixtureDef b2Fixture; b2Fixture.shape = &circle; b2Fixture.density = 0.6f; b2Fixture.friction = 0.0f; b2Fixture.restitution = 0.8f; ball->CreateFixture(&b2Fixture); return;}
<p> </p> 当注释掉init()中的addEdge()后小球可以正常下落,但是按照上面代码运行后小球会被卡在屏幕中央,网上找了一下答案,在stack overflow中有关于增加边界的回答,和我做的对照一下没有什么差别,实在想不出来为什么了。</p> <p> </p>