I am adding Box2D polygon's to my world and I can't figure out how to add texture to only the polygon shape. The polygon is a triangle and using the CGRectMake() for the rect: parameter while initializing my sprite gives me a sprite larger then my polygon.
This is my method that adds the polygon (spring) within the scene
-(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);
}
and this is the method, within the class, where I initiate the spring and the springs sprite.
-(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;
}
How do I initialize a sprite, with a texture, for a polygon? And make only the shape of the polygon have the texture? Thanks!
Not entirely sure but I think you may be a bit confused on the use of textures in Cocos2D and collision space in Box2D. You can't have the texture for the sprite be applied to the exact extents of the collision polygon unless you start getting into some of the specifics of texture coordinates but I don't think this will be the result you want. Usually what is done...
Hope I'm not assuming to much in what you don't know here. Let me know if this helps or if you have any other questions.