lunes, 2 de abril de 2012

Cocos2D - Dibujar cuadrícula


Dibujamos una cuadricula de tamaño kTileSize definido como constante en el .h.



- (void)draw

{

   // get the device screen size.
    CGSize winSize = [[CCDirector sharedDirector] winSize];

    // set line smoothing
    glEnable(GL_LINE_SMOOTH);

    for (int i=4; i<winSize.height; i++)
    {
        CGPoint point1 = ccp(i*kTileSize, winSize.height - kTileSize);
        CGPoint point2 = ccp(i*kTileSize, kTileSize);

        // set line smoothing
        glEnable(GL_LINE_SMOOTH);

       
        // set line width
        glLineWidth(0.4f);

        // set line color.
        glColor4f(0, 0, 0, 1.0);

        ccDrawLine(point1, point2);

    }
   

    for (int i=0; i<winSize.width; i++)
    {

        CGPoint point1 = ccp(winSize.width - kTileSize, i*kTileSize);
        CGPoint point2 = ccp(kTileSize, i*kTileSize);


        // set line smoothing
        glEnable(GL_LINE_STRIP);


        // set line width
        glLineWidth(0.4f);


        // set line color.
        glColor4f(0, 0, 0, 1.0);

        ccDrawLine(point1, point2);

    }    

}

sábado, 24 de marzo de 2012

COCOS2D - Check if your sprite is touched and then drag and drop

If you want to drag and drop your sprite only if you touch it you can use this function. My sprite dimensions are 14x14, that's why I check +- 7.


-(void)ccTouchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {
   
   
    UITouch* touch = [touches anyObject];
    CGPoint touchLocation = [touch locationInView: touch.view];
    touchLocation = [[CCDirector sharedDirector] convertToGL: touchLocation];
   
    if (isFirstTouch)
    {
   
        if (( (touchLocation.x >= (mySprite.position.x - 7)) &&  (touchLocation.x <= (mySprite.position.x +7) )) &&  ( (touchLocation.y >= (mySprite.position.y - 7)) &&  (touchLocation.y <= (mySprite.position.y +7) )))
        {        
            [mySprite setPosition:ccp(touchLocation.x , touchLocation.y )];
           isFirstTouch = NO;
        }
    }
    else
    {      
        [mySprite setPosition:ccp(touchLocation.x , touchLocation.y )];
}




- (void)ccTouchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
    isFirstTouch = YES;
}

Cocos2d iOS 5.1 - Drag and drop a sprite

- (void)ccTouchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
    UITouch *touch = [touches anyObject];
    CGPoint location = [touch locationInView: [touch view]];
 
    [mySprite setPosition:ccp(location.x , location.y )];
}