Previous Entry Share Next Entry
How to make a textured triangle Sprite from rectangular Texture in cocos2d 3.9?
fedoraus


I hope this small example will help you to understand PolygonInfo class and how it can be used to obtain textured polygons.

//we are making sprite with the same height and width
float width=400;
float height = 400;
auto mySprite = Sprite::create();
//create a PolygonInfo object to store all the data needed for polygon drawing
PolygonInfo inf;
// assigning texture file
inf.filename = "texture.png";
// setting the number of vertices in the desired polygon (3 because triangle)
inf.triangles.vertCount = 3;
// allocating memory for vertices (vertex position on the screen, vertex color Color4B, corresponding texture point)
inf.triangles.verts = new V3F_C4B_T2F[inf.triangles.vertCount];
// triangles are drawn based on the indices of vertices, hence the count is always divisible by 3
inf.triangles.indexCount = 3;
// the triangle are actually polygon vertices stored in inf.triangles.verts. To draw one triangle one provides a set of 3 indices
inf.triangles.indices = new unsigned short[info.triangles.indexCount];
//Now setting up triangle vertices
//first, lower left point
inf.triangles.verts[0].vertices = Vec3(0, 0, 0);
inf.triangles.verts[0].texCoords = Tex2F(0, 0);
inf.triangles.verts[0].colors = = Color4B(255, 255, 255, 255);

//second, lower right point
inf.triangles.verts[1].vertices = Vec3(width, 0, 0);
inf.triangles.verts[1].texCoords = Tex2F(1.0, 0);
inf.triangles.verts[1].colors = = Color4B(255, 255, 255, 255);
//third, top point
inf.triangles.verts[2].vertices = Vec3(width/2, height, 0);
inf.triangles.verts[2].texCoords = Tex2F(0.5, 1.0);
inf.triangles.verts[2].colors = = Color4B(255, 255, 255, 255);
// setting the vertex indices to draw polygon
inf.triangles.indices[0] = 0;
inf.triangles.indices[1] = 1;
inf.triangles.indices[2] = 2;
//setting the rectangle containing the sprite
inf.rect = Rect(Vec2(0, 0), Size(width, height));
mySprite->initWithPolygon(inf);
addChild(mySprite);

?

Log in

No account? Create an account