升级到cocos2d-iphone 2.0版后,我遇到了绘制对象的坐标问题。据我所知,我已正确升级了所有模板,但仍存在问题。例如,在“Learning Cocos2D”一书(box2D第10章)中,我已经实现了几个简单的方法来创建第一个createGround和createBoxAtLocation。第一个方法是从init调用的,如下所示:
- (void)createGround {
CGSize winSize = [[CCDirector sharedDirector] winSize];
// Set up the Box2D coordinates that correspond to the four corners of the ground boundary
float32 margin = 10.0f;
b2Vec2 lowerLeft = b2Vec2(margin/PTM_RATIO, margin/PTM_RATIO);
b2Vec2 lowerRight = b2Vec2((winSize.width-margin)/PTM_RATIO, margin/PTM_RATIO);
b2Vec2 upperRight = b2Vec2((winSize.width-margin)/PTM_RATIO,
(winSize.height-margin)/PTM_RATIO);
b2Vec2 upperLeft = b2Vec2(margin/PTM_RATIO,
(winSize.height-margin)/PTM_RATIO);
// Define the static container body, which will provide the collisions at screen borders.
b2BodyDef screenBorderDef;
screenBorderDef.position.Set(0, 0);
b2Body* screenBorderBody = world->CreateBody(&screenBorderDef);
b2EdgeShape screenBorderShape;
// Create fixtures for the four borders (the border shape is re-used)
screenBorderShape.Set(lowerLeft, lowerRight);
screenBorderBody->CreateFixture(&screenBorderShape, 0);
screenBorderShape.Set(lowerRight, upperRight);
screenBorderBody->CreateFixture(&screenBorderShape, 0);
screenBorderShape.Set(upperRight, upperLeft);
screenBorderBody->CreateFixture(&screenBorderShape, 0);
screenBorderShape.Set(upperLeft, lowerLeft);
screenBorderBody->CreateFixture(&screenBorderShape, 0);
}
这应该在屏幕边缘绘制一个绿色边界,边距为10点。但是,我只能在底部和左边看到绿色边界。顶部边缘和右边缘分别以屏幕高度和宽度的2倍绘制。
在同一个Box2D示例中,将在用户触摸屏幕的位置绘制一个框。当用户触摸屏幕时,将使用触摸位置调用createBoxAtLocation方法。触摸位置坐标位于cocos2d点坐标中,并且在您期望的范围内。下面是createBoxAtLocation方法:
- (void)createBoxAtLocation:(CGPoint)location
withSize:(CGSize)size
{
// First create a body
b2BodyDef bodyDef;
bodyDef.type = b2_dynamicBody; // This box is a dynamic body (movement handled by box2d)
bodyDef.position = b2Vec2(location.x/PTM_RATIO, // convert the point location to meters location
location.y/PTM_RATIO);
bodyDef.allowSleep = false;
b2Body *body = world->CreateBody(&bodyDef);
// Now create one or more fixtures to add to the body.
// To do this, you must first create a shape. In this case, we are creating a square box
b2PolygonShape shape;
shape.SetAsBox(size.width/2/PTM_RATIO, size.height/2/PTM_RATIO); // SetAsBox takes half dimensions as parameters
b2FixtureDef fixtureDef;
fixtureDef.shape = &shape;
fixtureDef.density = 1.0; // set density. The higher the number, the heavier it is
body->CreateFixture(&fixtureDef);
}
例如,如果触摸位置是193,190.5的点坐标(在iphone视网膜显示器上),则createBoxAtLocation方法将在点坐标386,381处绘制一个框,即使location.x = 193和location.y = 190.5。请注意,bodyDef.position的box2d坐标为3.86,3.81,因为PTM_RATIO为50。
我还可以说当我运行模拟器并选择iphone(非视网膜)作为硬件时,会在适当的位置创建框,createGround会在屏幕空间内生成适当的边界。我还可以说代码识别所有设备的正确尺寸屏幕(例如cocos2d打印出cocos2d:表面尺寸:iphone的480x320和cocos2d:iphone 3.5视网膜的表面尺寸:960x640)。最后,我运行了调试器并深入到绘图程序中。据我所知和理解,绘图程序已知正确的box2d坐标。但是这个盒子只是以比视网膜显示器的2倍的坐标显示。
我怀疑createGround的问题和createBoxAtLocation的问题都是一样的。我确信有一个简单的解决方案,但我无法弄清楚。有什么建议?