《Cocos2d-x for iPhone游戏开发实例详解---1.3 为精灵着色》

《Cocos2d-x for iPhone游戏开发实例详解》系列博文,基于 人民邮电出版社 《Cocos2d for iPhone游戏开发实例详解》一书,使用Cocosd-x技术重写。示例代码中所引用的相关资料归于原书作者 Nathan Burba 以及出版社所有,本系列博文提供的C++版代码仅供学习使用。

======================================================================================

开发环境:

  Cocos2d-x  cocos2d-2.1rc0-x-2.1.2-hotfix.zip @ Apr.08, 2013

  MacBook Pro 13'  Mountain Lion 10.8.3

  Xcode 4.6

  iPhone5   IOS 6.1.4

======================================================================================


本章 代码相对于中文翻译版有些许出入,以英文原版Cocos2d.for.iPhone.1.Game.Development.Cookbook Coder Source 为基准修改。

本示例展示了精灵的着色方法。


//****************************************************************************************************
//            Author:          Last Ranker
//            DateTime:        2013年08月17日
//            SearchMe:        http://blog.csdn.net/lastranker
//            Email:           tubufeng@foxmail.com
//
//****************************************************************************************************
//
//  ColoringSprites.h
//  Chapter_1
//
//  Created by Last Ranker on 13-8-17.
//
//

#ifndef __Chapter_1__ColoringSprites__
#define __Chapter_1__ColoringSprites__

#include <iostream>
#include "cocos2d.h"
using namespace cocos2d;
enum {
	TAG_FADE_TO_BLACK = 0,
	TAG_FADE_TO_WHITE = 1,
	TAG_FADE_SPRITE = 2,
	TAG_MOUNTAIN_BG = 3,
	TAG_SUN_BG = 4,
	TAG_GOOD_SAMURAI = 5,
	TAG_BAD_SAMURAI = 6,
	TAG_GROUND_GRADIENT = 7,
	TAG_RED_GRADIENT = 8
};
class ColoringSprite:public cocos2d::CCLayer
{
public:
    virtual bool init();
    static cocos2d::CCScene * scene();
    CCLayer * runRecipe();
    void initButtons();
    void drawColorSpriteAt(CCPoint postion,CCRect rect,ccColor3B color,float z);
    void glowAt(CCPoint position,CCSize size,ccColor3B color,float rotation,CCSprite * sprite);
    void fadeToBlackCallback(CCObject* pSender);
    void fadeToWhiteCallback(CCObject* pSender);
    CREATE_FUNC(ColoringSprite);
};
#endif /* defined(__Chapter_1__ColoringSprites__) */

//****************************************************************************************************
//            Author:          Last Ranker
//            DateTime:        2013年08月17日
//            SearchMe:        http://blog.csdn.net/lastranker
//            Email:           tubufeng@foxmail.com
//
//****************************************************************************************************
//
//  ColoringSprites.cpp
//  Chapter_1
//
//  Created by Last Ranker on 13-8-17.
//
//

#include "ColoringSprites.h"
using namespace cocos2d;
CCScene * ColoringSprite::scene()
{
    CCScene *scene=CCScene::create();
    ColoringSprite *layer=ColoringSprite::create();
    scene->addChild(layer);
    return scene;
    
}

bool ColoringSprite::init()
{
    //
    // 1. super init first
    if ( !CCLayer::init() )
    {
        return false;
    }
    runRecipe();
    return true;
}
void ColoringSprite::initButtons()
{
    //'Fade to Black' button
    CCMenuItemFont::setFontSize(16);
    
    CCMenuItemFont *fadeToBlack=CCMenuItemFont::create("FADE TO BLACK", this, menu_selector(ColoringSprite::fadeToBlackCallback));
    CCMenu *fadeToBlackMenu=CCMenu::create(fadeToBlack,NULL);
    fadeToBlackMenu->setPosition(ccp(180, 20));
    this->addChild(fadeToBlackMenu, 4, TAG_FADE_TO_BLACK);
    //'Fade to White' button
    CCMenuItemFont *fadeToWhite=CCMenuItemFont::create("FADE TO WHITE", this,menu_selector(ColoringSprite::fadeToWhiteCallback));
    CCMenu *fadeToWhiteMenu=CCMenu::create(fadeToWhite,NULL);
    fadeToWhiteMenu->setPosition(ccp(300, 20));
    this->addChild(fadeToWhiteMenu, 4, TAG_FADE_TO_WHITE);
}
CCLayer * ColoringSprite::runRecipe()
{
    initButtons();
    
    //The Fade Scene Sprite
    CCSprite *fadeSprite=CCSprite::create("blank.png");
    fadeSprite->setOpacity(0);
    fadeSprite->setPosition(ccp(240, 160));
    fadeSprite->setTextureRect(CCRect(0,0,480,320));
    this->addChild(fadeSprite, 3, TAG_FADE_SPRITE);
    
    //Draw the sky using blank.png
    this->drawColorSpriteAt(ccp(240, 190), CCRect(0, 0, 480, 260), ccc3(150, 200, 200), 0);
    
    //Draw the sun
    CCSprite *sun=CCSprite::create("fire.png");
    sun->setPosition(ccp(50, 230));
    sun->setScale(3.0f);
    sun->setColor(ccc3(255, 255, 0));
    this->addChild(sun, 0, TAG_SUN_BG);
    
    //Draw some mountains in the background
    CCSprite *mountains=CCSprite::create("mountains.png");
    mountains->setPosition(ccp(250, 200));
    mountains->setScale(0.6f);
    this->addChild(mountains, 0, TAG_MOUNTAIN_BG);
	
	//Add a gradient below the mountains
    CCLayerGradient *groundGraient=CCLayerGradient::create(ccc4(61, 33, 62, 255), ccc4(65, 89, 54, 255), ccp(0, -1));
    groundGraient->setContentSize(CCSizeMake(480, 100));
    groundGraient->setPosition(ccp(0, 50));
    this->addChild(groundGraient, 0, TAG_GROUND_GRADIENT);
    
    //Add a sinister red glow gradient behind the evil samurai
    CCLayerGradient *redGradient=CCLayerGradient::create(ccc4(0, 0, 0, 0), ccc4(255, 0, 0, 100), ccp(1, 0));
    redGradient->setContentSize(CCSizeMake(200, 200));
    redGradient->setPosition(ccp(280, 60));
    this->addChild(redGradient, 2, TAG_RED_GRADIENT);
	
	//Draw dramatic movie bars
    this->drawColorSpriteAt(ccp(240, 290), CCRectMake(0, 0, 480, 60), ccc3(0, 0, 0), 2);
    this->drawColorSpriteAt(ccp(240, 30), CCRectMake(0, 0, 480, 60), ccc3(0, 0, 0), 2);
    
    //Draw the good samurai
    CCSprite *goodSamurai=CCSprite::create("samurai_good.png");
    goodSamurai->setAnchorPoint(ccp(0.5f, 0));
    goodSamurai->setPosition(ccp(100, 70));
    goodSamurai->setScale(0.5f);
    this->addChild(goodSamurai, 1, TAG_GOOD_SAMURAI);
	
	//Draw the evil samurai
    CCSprite *evilSamurai=CCSprite::create("samurai_evil.png");
    evilSamurai->setAnchorPoint(ccp(0.5f, 0));
    evilSamurai->setPosition(ccp(370, 70));
    evilSamurai->setFlipX(true);
    evilSamurai->setScale(0.5f);
    this->addChild(evilSamurai, 1,TAG_GOOD_SAMURAI);
    
    // Make the swords glow
    this->glowAt(ccp(230, 280), CCSizeMake(3.0f, 11.0f), ccc3(0, 230, 255), 45.0f, goodSamurai);
	this->glowAt(ccp(70, 280), CCSizeMake(3.0f, 11.0f), ccc3(255, 200, 2), -45.0f, evilSamurai);
    
	return  this;
                               
}

/* Create a glow effect */
void ColoringSprite::drawColorSpriteAt(CCPoint postion,CCRect rect,ccColor3B color,float z)
{
    CCSprite *sprite=CCSprite::create("blank.png", rect);
    sprite->setPosition(postion);
    sprite->setColor(color);
    this->addChild(sprite,z);
}
/* Create a glow effect */
void ColoringSprite::glowAt(CCPoint position,CCSize size,ccColor3B color,float rotation,CCSprite * sprite)
{
    CCSprite *glowSpirte=CCSprite::create("fire.png");
    glowSpirte->setColor(color);
    glowSpirte->setPosition(position);
    glowSpirte->setRotation(rotation);
    glowSpirte->setBlendFunc((ccBlendFunc){GL_ONE,GL_ONE});
    
    glowSpirte->runAction(CCRepeatForever::create((CCActionInterval*)CCSequence::create(CCScaleTo::create(0.9f, size.width, size.height),CCScaleTo::create(0.9f, size.width*0.75f, size.height*0.75f),NULL)));
    glowSpirte->runAction(CCRepeatForever::create((CCActionInterval*)CCSequence::create(CCFadeTo::create(0.9f, 150),CCFadeTo::create(0.9f, 255),NULL)));
    sprite->addChild(glowSpirte);
    
}
/* Fade the scene to black */
void ColoringSprite::fadeToBlackCallback(CCObject *pSender)
{
    CCSprite *fadeSprite=(CCSprite*)this->getChildByTag(TAG_FADE_SPRITE);
    fadeSprite->stopAllActions();
    fadeSprite->setColor(ccc3(0, 0, 0));
    fadeSprite->setOpacity(0.0f);
    fadeSprite->runAction((CCActionInterval*)CCSequence::create(CCFadeIn::create(2.0f),CCFadeOut::create(2.0f),NULL));
}
/* Fade the scene to white */
void ColoringSprite::fadeToWhiteCallback(CCObject *pSender)
{
    CCSprite *fadeSprite=(CCSprite*)this->getChildByTag(TAG_FADE_SPRITE);
    fadeSprite->stopAllActions();
    fadeSprite->setColor(ccc3(255,255,255));
    fadeSprite->setOpacity(0.0f);
    fadeSprite->runAction((CCActionInterval*)CCSequence::create(CCFadeIn::create(2.0f),CCFadeOut::create(2.0f),NULL));
    
}


This recipe shows a number of color based techniques.

f Setting sprite color:
The simplest use of color involves setting the color of a sprite using the following

method:

       -(void) setColor:(ccColor3B)color;

Setting sprite color effectively reduces the color you can display but it allows someprogrammatic flexibility in drawing. In this recipe we use setColorfor a numberof things, including drawing a blue sky, a yellow sun, black "dramatic movie bars",and more.

ccColor3B is a C struct which contains threeGLubyte variables. Use the followinghelper macro to createccColor3B structures:

      ccColor3B ccc3(const GLubyte r, const GLubyte g, const GLubyte
      b);

Cocos2d also specifies a number of pre-defined colors as constants. These includethe following:

       ccWHITE, ccYELLOW, ccBLUE, ccGREEN, ccRED,
       ccMAGENTA, ccBLACK, ccORANGE, ccGRAY

f Fading to a color:

To fade a scene to a specific color we use theblank.png technique we went over inthe last recipe. We first draw a sprite as large as the screen, then color the sprite tothe color we want to fade to, and then finally run a CCFadeInaction on the sprite tofade to that color:

       [fadeSprite setColor:ccc3(255,255,255)];
       [fadeSprite setOpacity:0.0f];
       [fadeSprite runAction: [CCFadeIn actionWithDuration:2.0f] ];

f Using CCGradientLayer:

Using the CCGradientLayer class we can programmatically create gradients. Tomake the mountains in the background fade into the ground the two samurai arestanding on we created a gradient using this method:

         CCGradientLayer *gradientLayer = [CCGradientLayer layerWithColor
       :ccc4(61,33,62,255) toColor:ccc4(65,89,54,255) withDirection:CCGra
       dientDirectionT_B width:480 height:100];
         [gradientLayer setPosition:ccp(0,50)];
         [self addChild:gradientLayer z:0 tag:TAG_GROUND_GRADIENT];

Because CCGradientLayer lets you control opacity as well as color, it has manyuses. As you can see there is also a sinister red glow behind the evil samurai.


page25image18992

f Making a sprite glow:

To make the swords in the demo glow we use subtle color manipulation, additiveblending and fading and scaling actions. First we load thefire.pngsprite suppliedby Cocos2d. By changing its X and Y scale independently we can make it thinner orfatter. Once you have the desired scale ratio (in this demo we use x:y 3:11 becausethe sword is so thin) you can constantly scale and fade the sprite in and out to givesome life to the effect. You also need to set the blend function to{ GL_ONE, GL_ONE }for additive blending. Finally this effect sprite is added to the actual sprite tomake it seem like it glows.

       CCSprite *glowSprite = [CCSprite spriteWithFile:@"fire.png"];
         [glowSprite setColor:color];
         [glowSprite setPosition:position];
         [glowSprite setRotation:rotation];
         [glowSprite setBlendFunc: (ccBlendFunc) { GL_ONE, GL_ONE }];
         [glowSprite runAction: [CCRepeatForever actionWithAction:
         [CCSequence actions:[CCScaleTo actionWithDuration:0.9f
       scaleX:size.width scaleY:size.height], [CCScaleTo
       actionWithDuration:0.9f scaleX:size.width*0.75f scaleY:size.
       height*0.75f], nil] ] ];
         [glowSprite runAction: [CCRepeatForever actionWithAction:
         [CCSequence actions:[CCFadeTo actionWithDuration:0.9f
       opacity:150], [CCFadeTo actionWithDuration:0.9f opacity:255], nil]
       ] ];
         [sprite addChild:glowSprite];

源代码:http://pan.baidu.com/share/link?shareid=1591617903&uk=1962963338

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值