Draw lines & shapes using ccDrawLine & glColor4f

Using this tutorial, I will describe “How to draw lines & shapes in Cocos2d?”.

First of all, Let’s have an look what we are going to have as an output.

Draw Shapes in Cocos2d

Draw Shapes in Cocos2d

Here, we have to determine the 5 points to create a star.

A point at left center ( x = 0, y = WindowSize.height/2 )

A point at right center ( x = WindowSize.width, y = WindowSize.height/2 )

A point at top center ( x = WindowSize.width/2, y = WindowSize.height )

Two points at the bottom as illustrated in image.

Point 1 at bottom ( x = WindowSize.width/3, y = 0 )

Point 2 at bottom ( x = WindowSize.width/3*2, y = 0 )

Now, To draw lines in Cocos2D, first of all open the Layer.m file whichever you are using. i.e. HelloWorldLayer.m file. & place following code. Go through the comments placed in code which will help you to understand the code.

#import "HelloWorldLayer.h"

@implementation HelloWorldLayer

+(CCScene *) scene {
	CCScene *scene = [CCScene node];
	HelloWorldLayer *layer = [HelloWorldLayer node];
	[scene addChild: layer];
	return scene;
}

-(id) init {
	if( (self=[super init])) {
	}
	return self;
}

// override this method
- (void)draw {
    // get the device screen size.
    CGSize winSize = [[CCDirector sharedDirector] winSize];

    // determine the center point.
    CGPoint center = ccp(winSize.width/2,winSize.height/2);

    // determine the left center point.
    CGPoint left = ccp(0,center.y);

    // determine the right center point.
    CGPoint right = ccp(winSize.width,center.y);

    // determine the top center point.
    CGPoint top = ccp(center.x,winSize.height);

    // determine the bottom point 1.
    CGPoint bottom1 = ccp(winSize.width/3,0);

    // determine the bottom point 2.
    CGPoint bottom2 = ccp((winSize.width/3*2),0);

    // set line smoothing
    glEnable(GL_LINE_SMOOTH);

    // set line width
    glLineWidth(3.0f);

    // set line color.
    glColor4f(0.8, 1.0, 0.76, 1.0);

    // draw line from a vector to other vector.
    ccDrawLine(bottom1,top);

    // draw line from a vector to other vector. same for others.
    ccDrawLine(top, bottom2);
    ccDrawLine(bottom2, left);
    ccDrawLine(left, right);
    ccDrawLine(right, bottom1);
}

 

Grab the sample code from here.

Thanks & Regards,

Neon Spark.

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *