0
点赞
收藏
分享

微信扫一扫

Cocos2d-x入门(计算机游戏开发课程笔记)

我阿霆哥 2022-03-12 阅读 177

Cocos2d-x入门(计算机游戏开发课程笔记)

文章目录

查看版本

在控制台输入命令cocos -v可以查看当前版本。

# 输入
cocos -v
# 输出如下:
cocos2d-x-3.15.1
Cocos Console 2.3

创建项目

  • 使用 cocos new 命令创建新项目,基础命令格式如下:

    cocos new 项目名称 -p 包名 -l 语言类型 -d 目录
    

    完整的创建格式如下:

    cocos new [-h] [-p PACKAGE_NAME] [-d DIRECTORY] [-t TEMPLATE_NAME]
                     [--ios-bundleid IOS_BUNDLEID] [--mac-bundleid MAC_BUNDLEID]
                     [-e ENGINE_PATH] [--portrait] -l {cpp,lua,js}
                     [PROJECT_NAME]
    

    示例:

    # 基础操作
    cocos new HelloWorld –p com.coocs2dx.org –l cpp –d myproject
    # 最简指令
    cocos new YGame -l cpp
    

参数意义:

  • h(help):帮助
  • p(package):类似java的包名,可以省略。
  • l(language):语言类型,不可省略。可以选择 cpp,lua,js
  • d(directory):指定目录,可以省略,省略就在当前目录下生成。

基础架构

1. 命名空间

USING_NS_CC;
#  OR
using namespace cocos2d;

2. 程序入口函数

函数:WINAPI _tWinMain

//创建实例
AppDelegate app; //单例
return Application::getInstance()->run();//显示窗口

3. AppDelegate.h

applicationDidFinishLaunching()
  • 初始化导演
auto director = Director::getInstance();
  • 创建第一个场景
auto scene = HelloWorld::createScene();
  • 启动场景
director->runWithScene(scene);
  • 导演的工作
auto glview = director->getOpenGLView(); //Open Graphics Library
if(!glview){
    ...
        director->setOpenGLView(glview);
}
// 开启FPS
director->setDisplayStats(true);
//设置
director->setAnimationInterval(1.0f/60);//默认参数
//设置分辨率

  • 分辨率
    • design(这个是自己设计的窗口大小)
    • small
    • medium
    • large
applicationDidEnterBackground()
applicationWillEnterForeground()

HelloWorldScene.h

构建简单场景

auto dirs = Director::getInstance();
Size visibleSize = dirs->getVisibleSize();

auto myScene = Scene::create();

auto label1 = Label::createWithTTF("My Game","Marker Felt.ttf",36);
label1->setPosition(Vec2(orgin.x+visibleSize.width/2),
                    orgin.y+ visibleSize.height/2);
myScene->addChild(label1);

auto sprite1 = Sprite::create("mySprite.png");
sprite1->setPosition(Vec2(100,100));

myScene->addChild(sprite1);

字体

位图字体 (BMFont)

auto label = Label::createWithBMFont("bitmapRed.fnt");

ps: 不适合缩放,性能好

TrueTtpe字体 (TTF)

便捷,渲染速度慢,消耗性能

多个相同属性的Label对象可以创建一个TTFConfig对象统一配置

系统字体 (SystemFont)

标签效果

  • 阴影
  • 描边
  • 发光

动画Animation

//Animation存放数据
auto animation = Animation::create();
//封装
animation->addSpriteFrameWithFile("player1.png");
animation->addSpriteFrameWithFile("player2.png");
//设定间隔
animation->setDelayPerUnit(0.1f);
//动画呈现
auto animate=Animate::create(animation);
sprite->runAction(animate);

锚点

精灵的锚点一般为:0.5 0.5

Menu, Layer 0 0

内存管理机制

自动释放池 AutoreleasePool

方法:

autorelease();
//Example:
Object *rpet =  new Object();
rpet->autorelease();

手动修改引用计数

  • new 创建对象,引用计数 加1
  • 调用 retain() 方法,引用计数 加1
  • 调用 release() 方法,引用计数 减1
  • 若引用计数为0,回收对象内存

交互响应机制

基本元素

  • 事件监听器:EventListener

  • 事件分发器:EventDispatcher

  • 事件对象: Eg: Touch

事件分发机制:

  1. 通过点击位置进行点击范围判断,来确定执行哪一个sprite的事件监听器
  2. 如果该位置存在重叠的sprite绑定了相同的事件,则依据优先级)(SceneGraphPriority显示优先级或
    FixedPriority固定优先级)来顺序执行函数回调
  3. 通过设置swallowTouches属性为true,并在onTouchBegan中返回true或者false来决定是否阻止事件
    的顺序传递。如果onTouchBegan返回true, 且swallowTouches为true, 则事件被吞沒事件的顺序
    传递则被阻止。

事件的吞没

listener->setSwallowTouches(true);

监听器

  • EventListenerTouch -响应触摸事件
  • EventlistenerKeyboard - 响应键盘事件
  • EventlistenerAcceleration - 响应加速度事件
  • EventListenMouse - 响应鼠标事件
  • EventListenerCustom -响应自定义事件

交互界面设计

CocosStudio–UI Editor

相关概念:

游戏视角:

FPS:第一视角令玩家和游戏主人公融为一体

RTS:俯视视角令玩家有掌控全局的感觉

色彩设计:

颜色三要素:

(1)亮度(brightness / lightness):也叫明度,体现颜色的明暗度;

(2)色相(hue):也叫色泽,是色彩的相貌和区别色彩种类的名称, 如红、橙、黄、绿、青等;

(3)纯度(saturation):色彩的纯净程度,又称饱和度。


游戏界面UI

设计实例–贪食豆

•对用户触摸进行响应

virtual bool onTouchBegan (Touch *pTouch, Event *pEvent) ;
virtual void onTouchMoved (Touch *pTouch,Event *pEvent) ;
virtual void onTouchEnded (Touch *pTouch,Event *pEvent) ;

• 封装摇杆类Joystick

Vec2 m_ centerPoint;    //摇杆中心
Vec2 m_ currentPoint:   //摇杆当前位置
float m radius;    //摇杆半径
Sprite* m_ jsSprite;  //摇杆控制点

UI应用

场景切换

auto myScene = Scene: :create();

//runWithScene()用于开始游戏, 加载第一个场景。只用于第一个场景!
Director: :getInstance()->runWithScene (myScene);

//replaceScene()使用传入的场景替换当前场景来切换画面,当前场景被释放。这是切换场景时最常用的方法。
Director::getInstance()->replaceScene (myScene);

二维动画

概述

FPS是图像领域中的定义,是指画面每秒传输帧数,通俗来讲就是指动画或视频的画面数。

**电影:**24fps

**电视(PAL):**25fps

**电视(NTSC):**30fps

计算机动画技术

基本动画技术
  • 逐帧动画

    例子:小小动画

    逐帧保存,体积大

    制作麻烦,费时

    灵活性高,画面细腻

  • 关键帧动画

仅保留关键帧

脚本驱动的动画技术
  • 主要用于游戏开发
骨骼动画技术

常见动画制作软件

flash ,maya ,3Dmax

Cocos2d-x的动作类 Action

MoveTo MoveBy
auto moveTo = MoveTo::create(2,Vec(50,10));//使用2秒到达。。。
sprite1->runAction(moveTo);
auto moveBy = MoveBy::create(2,Vec(500,sprite->getPositionY()));
DelayTime
// Delay 一create a small delay 
auto delay = DelayTime: :create(1);

auto seq = Sequence: :create(moveBy, delay, moveTo, nullptr);
mySprite->runAction(seq);

旋转RotateTo RotateBy

顺时针旋转

auto mySprite = Sprite::create( "mysprite. png");
// Rotates a Node to the specific angle over 2 seconds
auto rotateTo = RotateTo::create(2.0f, 40.0f);
mySprite->runAction(rotateTo);
// Rotates a Node clockwise by 40 degree over 2 seconds
auto rotateBy = RotateBy::create(2.0f, 40. 0f);
mySprite- >runAction(rotateBy);
缩放 ScaleBy ScaleTo
auto mySprite = Sprite: :create("mysprite.png");
// Scale uniformly by 3x over 2 seconds
auto scaleBy = ScaleBy: :create(2.0f, 3.0f);
mySprite->runAction(scaleBy);
// Scale to uniformly to 3x over 2 seconds
auto scaleTo = ScaleTo::create(2.0f, 3.0f);
mySprite->runAction(scaleTo);

淡入淡出

使用FadeIn Fade0ut 完成节点对象的淡入,淡出。
FadeIn修改节点对象的透明度属性,从完全透明到完全不透明,FadeOut相反。

auto mySprite = Sprite: :create("mysprite.png");
// fades in the sprite in 1 seconds
auto fadeIn = FadeIn::create(1.0f);
mySprite ->runAction(fadeIn);
// fades out the sprite in 2 seconds
auto fadeOut = Fade0ut::create(2.0f);
mySprite->runAction(fade0ut);
// 修改透明度
auto fadeTo = FadeTo::create(2.0f, 120.0f);

色彩混合

使用TintTo , TintBy将一个实现了NodeRGB协议的节点对象进行色彩混合。

auto mySprite = Sprite::create( "mysprite . png");
// Tints a node to the specified RGB values
auto tintTo = TintTo: :create(2.0f,120.0f, 232.0f, 254.0f);
mySprite- >runAction(tintTo);
// Tints a node BY the delta of the specified RGB values .
auto tintBy = TintBy::create(2.0f, 120.0f, 232.0f, 254.0f);
mySprite->runAction(tintBy);

序列 Sequence
auto moveTo = MoveTo::create(rand( % 5,Point (ball1->getPositionX(,-10));//移动动作
//当小球移动到屏幕下方时回调removeBall函数,移除小球
auto actionDone = CallFune::create (CC. _CALLBACK_ 0(HelloWorld: :removeBall,this, bal11)) ;
auto sequence = Sequence: :create (moveTo,actionDone, nullptr) ;
balll->runAction (sequence) ;//执行动作

Spawn

Spawn和Sequence 是非常相似的,区别是Spawn 同时执行所有的动作。Spawn 对象可以添加任意数量的动作和其它Spawn 对象。

auto mySpawn = Spawn::createWithTwoActions (moveBy, fadeTo);
mySprite->runAction(mySpawn);
动作克隆 Clone

必要性与实例:

错误示范

动作倒转 Reverse
// reverse a sequence, spawn or action
mySprite - >runAction( mySpawn->reverse());
倾斜动作 SkewTo/SkewBy

延时动作 继承自ActionInterval (后续的动作类 等同)

//参数: 持续时间,x轴上倾斜到的角度,y轴上倾斜到的角度
auto actionTo = SkewTo::create(2, 37.2f, -37.2f);
//参数: 持续时间,x轴上倾斜的角度,y轴上倾斜的角度
auto actionBy = SkewBy::create(2, 0.0f, -90.0f)
弹跳动作 JumpTo/JumpBy
//参数: 持续时间,跳跃的目的坐标,跳跃的高度,跳跃的次数
auto actionTo = JumpTo::create(2, Point(300,300), 50, 4);
//参数: 持续时间,跳跃的位移,跳跃的高度,跳跃的次数
auto actionBy = JumpBy::create(2, Point(300,0), 50, 4);
贝塞尔曲线动作 BezierTo/BezierBy
//参数: 获得当前屏幕大小
auto s = Director::getInstance()->getWinSize();
//新建一个贝塞尔曲线,定义它的控制点和结束点
ccBezierConfig bezier;
bezier.controlPoint_1 = Point(0, s.height/2);
bezier.controlPoint_2 = Point(300, -s.height/2);
bezier.endPosition = Point(300,100);
//创建一个贝塞尔曲线特效,参数:持续的时间,贝塞尔曲线
auto bezierForward = BezierBy::create(3, bezier);
闪烁Blink
//参数: 持续时间,闪烁次数
auto action1 = Blink::create(2, 10);
染色 TintTo/TintBy
//参数: 着色时间,红色、绿色、蓝色的着色目的值
auto action1 = TintTo::create(2, 255, 0, 255);
//参数: 着色时间,红色、绿色、蓝色的着色改变值
auto action2 = TintBy::create(2, -127, -255, -127)
重复和永久重复 Repeat/RepeatForever
auto act1 = RotateTo::create(1, 90);
auto act2 = RotateTo::create(1, 0);
auto seq = Sequence::create(act1, act2, NULL);
//参数: 需要永久重复执行的ActionInterval动作特效
auto rep1 = RepeatForever::create(seq);
//参数: 需要重复执行的ActionInterval动作特效,重复执行的次数
auto rep2 = Repeat::create( seq->clone(), 10)
线性变速 Speed
//参数: 要改变速度的ActionInterval类的目标动作,改变的速度倍率
auto action = Speed::create(RepeatForever::create(spawn), 0.5f);
曲线变速 ActionEase

曲线变速

  • EaseExponentialIn:指数缓冲动作。继承自Action。用于指数曲线 变化某个动作的速度。
  • EaseSineInOut:正弦缓冲。继承自Action。用于Sine曲线 改变某个动作的速度。
  • EaseElasticInOut:弹性缓冲。继承自Action。用于弹性曲线的改变某个动作的速度。
  • EaseBounceInOut:跳跃缓冲。继承自Action。用于跳跃曲线的改变某个动作的速度。
  • EaseBackInOut:回震缓冲。继承自Action。用于回震曲线 改变某个动作的速度。

举例:

//参数: 要改变速度的ActionInterval类的目标动作
auto move_ease_in = EaseExponentialIn::create(move->clone());
auto move_ease_out = EaseExponentialOut::create(move->clone());
auto move_ease = EaseExponentialInOut::create(move->clone());
    //移动到左下方(指数缓冲动作) Down Left
    auto moveToDL = MoveTo::create(time, Vec2(sprite->getPositionX() * 0.3, sprite->getPositionY() * 0.4));
    auto move_ease_out = EaseExponentialOut::create(moveToDL->clone());
显示/隐藏 节点对象Show / Hide
auto show = Show:create();
node->runAction(show);
切换节点对象的visible属性 ToggleVisibility
auto visibility = ToggleVisibility:create();
node->runAction(visibility)
跟随动作 Follow

不能用于组合动作中。

闪烁Blink
auto blink = Blink::create(time,3);
弹跳jump
auto jumpTo = JumpTo::create(2.0,Point(320,480),20,2);//花2s;每次跳跃高度为20;跳2次
auto jumpBy 类似

Cocos2d-x中的动画类

//动画auto animation=Animation::create();
– 封装一系列动画帧
• animation->addSpriteFrameWithFile(“player1.png”);
• animation->addSpriteFrameWithFile(“player2.png”);
– 可设定动画帧的播放间隔
• animation->setDelayPerUnit(0.1f);

// Animate
auto animate=Animate::create(animation); 
• sprite->runAction(animate);
导出骨骼动画
  • 骨骼动画类Armature

方法:

ArmatureDataManager::getInstance()->addArmatureFileInfo(".Exportjson");
arm = Armature::create("name");

arm->getAnimation()->play("run"); //开始
arm->getAnimation()->resume(); //继续
arm->getAnimation()->pause();  //暂停

监听特定动画结束帧 -> 还原布尔值

精灵Sprite

创建精灵

1. 使用图像创建
auto mySprite = Sprite::create("sprite.png");
2. 使用矩形
auto mySprite = Sprite::create("sprite.png",Rect(0,0,40,40));
3.使用图集
  • 加载图集

在使用图集时,首先将其全部加载到SpriteFrameCache中,SpriteFrameCache 是一个全局的缓存类 >缓存了添加到其中的SpriteFrame 对象,提高了精灵的访问速度。SpriteFrame 只加载1次,后续一直保存在SpriteFrameCache 中。

auto spritecache = SpriteFrameCache::getInstance();
spritecache->addSpriteFrameWithFile
  • 创建图集 Texture Packer

使用精灵缓存(时间效率提升)

auto newspriteFrame = SpriteFrameCache::getInstance()- >getSpriteFrameByName("Blue_ Front1. png”);
auto newSprite = Sprite::createWithSpriteFrame (newspriteFrame);

在这里插入图片描述

多边形精灵(空间效率提升)

绘制定点比绘制像素消耗少。

AutoPolygon
// Generate polygon info automatically.
auto pinfo = AutoPolygon: :generatePolygon("filename .png" );
// Create a sprite with polygon info.
auto sprite = Sprite: : create(pinfo);

帽子 + 武器 + 防御

bug:

没有挨揍动画

被打定住

怪物

动画没播放完 -》帧事件

白云

Cocos2d-x 工具集

Cocos Studio

动画编辑器 Animation Editor

关键帧产生中间帧技术
  1. 创建项目 – Animation Editor->文件->新建,创建新项目 Cocos2d-x动画编辑器•

  2. 导入资源 – 资源面板导入图片button.png Cocos2d-x动画编辑器•

  3. 编辑动画 – 在时间轴上在15帧和30帧处添加关键帧 Cocos2d-x动画编辑器•

  4. 导出动画 – 选择文件->导出项目 – 使用默认参数导出动画 Cocos2d-x动画编辑器 导出项目 导出完毕后,把导出的文件夹拷贝到cocos2d-x project的Resource文件夹下, 就能够在项目中使用了

骨骼动画绘制步骤
  1. 创建骨骼
  2. 绑定骨骼
  3. 绑定父子关系
    oPolygon 进行处理, 然后我们使用它生成的对象进行精灵的创建就能得到多边形精灵。
// Generate polygon info automatically.
auto pinfo = AutoPolygon: :generatePolygon("filename .png" );
// Create a sprite with polygon info.
auto sprite = Sprite: : create(pinfo);

帽子 + 武器 + 防御

bug:

没有挨揍动画

被打定住

怪物

动画没播放完 -》帧事件

白云

Cocos2d-x 工具集

Cocos Studio

动画编辑器 Animation Editor

关键帧产生中间帧技术
  1. 创建项目 – Animation Editor->文件->新建,创建新项目 Cocos2d-x动画编辑器•

  2. 导入资源 – 资源面板导入图片button.png Cocos2d-x动画编辑器•

  3. 编辑动画 – 在时间轴上在15帧和30帧处添加关键帧 Cocos2d-x动画编辑器•

  4. 导出动画 – 选择文件->导出项目 – 使用默认参数导出动画 Cocos2d-x动画编辑器 导出项目 导出完毕后,把导出的文件夹拷贝到cocos2d-x project的Resource文件夹下, 就能够在项目中使用了

骨骼动画绘制步骤
  1. 创建骨骼
  2. 绑定骨骼
  3. 绑定父子关系
  4. 编辑动画
举报

相关推荐

0 条评论