我正在将 Box2D 多边形添加到我的世界中,但我不知道如何仅将纹理添加到多边形形状。多边形是一个三角形,在初始化我的精灵时使用 CGRectMake() 作为 rect: 参数给我一个比我的多边形更大的精灵。
这是我在场景中添加多边形(弹簧)的方法
-(void) addSpring:(zSpring*)spring
{
[self addChild:spring.sprite];
CGPoint p = spring.coords;
//static triangle one
b2Vec2 vertices[3];
int32 count = 3;
vertices[0].Set(0.0f,0.0f);
vertices[1].Set(2.0f,0.0f);
vertices[2].Set(0.0f,1.0f);
b2BodyDef springBodyDef;
springBodyDef.type = b2_staticBody;
springBodyDef.position.Set(p.x/PTM_RATIO ,p.y/PTM_RATIO);
springBodyDef.userData = spring.sprite;
b2Body *body = world->CreateBody(&springBodyDef);
b2PolygonShape polygon;
polygon.Set(vertices, count);
b2FixtureDef springShapeDef;
springShapeDef.shape = &polygon;
springShapeDef.density = 1.0f;
springShapeDef.friction = 0.2f;
springShapeDef.restitution = 1.6f;
body->CreateFixture(&springShapeDef);
}
这是类中的方法,我在其中启动弹簧和弹簧精灵。
-(id)initWithCoords:(CGPoint)p withSpringType:(int)st
{
self.springType = st;
self.coords = p;
CCTexture2D *texture = [[CCTextureCache sharedTextureCache] addImage:@"metalTexture.png"];
// When initializing the sprite I want to make a polygon (triangle), not a rectangle
self.sprite = [[CCSprite alloc] initWithTexture:texture rect:CGRectMake(0, 0, 32, 32)];
self.sprite.position = ccp(p.x, p.y);
self.sprite.tag = 2;
return self;
}
如何为多边形初始化带有纹理的精灵?并且只让多边形的形状有质感?谢谢!