gpt4 book ai didi

objective-c - Box2D动态体掉屏

转载 作者:塔克拉玛干 更新时间:2023-11-02 20:26:15 26 4
gpt4 key购买 nike

我基本上有一个矩形物体(如矛)和一个地面体。问题是,当长矛撞到地面时,它不会反弹,而是从屏幕上掉下来。这是我的物理设置:(忽略球引用,它应该被称为矛(矩形))

-(id) init {

if( (self=[super init])) {

CGSize winSize = [CCDirector sharedDirector].winSize;

self.isAccelerometerEnabled = YES;
self.isTouchEnabled = YES;

// Create sprite and add it to the layer
_ball = [CCSprite spriteWithFile:@"SPEAR.png" rect:CGRectMake(0, 0, 100, 10)];
_ball.position = ccp(100, 100);
[self addChild:_ball];

// Create a world
b2Vec2 gravity = b2Vec2(0.0f, -20.0f);
bool doSleep = true;
_world = new b2World(gravity, doSleep);

// Create edges around the entire screen
b2BodyDef groundBodyDef;
groundBodyDef.position.Set(0,0);
b2Body *groundBody = _world->CreateBody(&groundBodyDef);
b2PolygonShape groundBox;
b2FixtureDef boxShapeDef;
boxShapeDef.shape = &groundBox;
groundBox.SetAsEdge(b2Vec2(0,0), b2Vec2(winSize.width/PTM_RATIO, 0));
groundBody->CreateFixture(&boxShapeDef);
groundBox.SetAsEdge(b2Vec2(0,0), b2Vec2(0, winSize.height/PTM_RATIO));
groundBody->CreateFixture(&boxShapeDef);
groundBox.SetAsEdge(b2Vec2(0, winSize.height/PTM_RATIO), b2Vec2(winSize.width/PTM_RATIO, winSize.height/PTM_RATIO));
groundBody->CreateFixture(&boxShapeDef);
groundBox.SetAsEdge(b2Vec2(winSize.width/PTM_RATIO, winSize.height/PTM_RATIO), b2Vec2(winSize.width/PTM_RATIO, 0));
groundBody->CreateFixture(&boxShapeDef);

// Create ball body and shape
b2BodyDef ballBodyDef;
ballBodyDef.type = b2_dynamicBody;
ballBodyDef.position.Set(100/PTM_RATIO, 100/PTM_RATIO);
ballBodyDef.userData = _ball;
b2Body *_body = _world->CreateBody(&ballBodyDef);


b2PolygonShape spearShape;
spearShape.SetAsBox(100/PTM_RATIO, 10/PTM_RATIO);
b2FixtureDef ballShapeDef;
ballShapeDef.shape = &spearShape;


ballShapeDef.density = 1.0f;
ballShapeDef.friction = 0.9f;
ballShapeDef.restitution = 0.89f;

b2Vec2 force;
force.Set(_body->GetLinearVelocity().x+5.0f, _body->GetLinearVelocity().y+10.0f);
_body->SetLinearVelocity(force);

[self schedule:@selector(tick:)];
}
return self;
}

- (void)tick:(ccTime) dt {

_world->Step(dt, 10, 10);
for(b2Body *b = _world->GetBodyList(); b; b=b->GetNext()) {
if (b->GetUserData() != NULL) {
CCSprite *ballData = (CCSprite *)b->GetUserData();
ballData.position = ccp(b->GetPosition().x * PTM_RATIO,
b->GetPosition().y * PTM_RATIO);
ballData.rotation = -1 * CC_RADIANS_TO_DEGREES(b->GetAngle());
}
}
}

最佳答案

我在您的代码中没有看到任何将形状附加到球和矛上的地方。如果 body 没有形状 - 它不会发生碰撞。

关于objective-c - Box2D动态体掉屏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6542740/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com