cocos creator v3.8体验归档

2024-06-18  本文已影响0人  说叁两事

快速开始

跟着Cocos Creator用户手册完成step by step教程即可快速熟悉Cocos Creator的应用。

可以通过右上角切换用户手册版本:


用户手册版本切换

IDE界面介绍

IDE管理

通过首页下载Cocos Dashboard,可以管理不同版本的Cocos Creator Editor

Cocos Dashboard Cocos Creator Editor

语言设置

通过下述配置可以修改界面语言:


界面语言

场景视角操作

在 3D 视图下,可以通过以下操作来移动和定位 场景编辑器 的视图:

渲染

列表渲染详见

资源类型

目前,Creator 支持 FBX 和 glTF 两种格式的模型文件。

动画

骨骼动画

对于mixamo官网来说,处理骨骼动画需满足:

mixamo下载TPose后,下载所需的不同without skin骨骼动画,分别导入blender中重命名骨骼动画(便于识别),然后删除场景中的所有要素

骨骼动画要素清除

最后导入TPose,进行下列步骤绑定骨骼动画:

绑定骨骼动画

在下方面板中[1]选择[2]动画摄影表,[3]选择动作编辑器,[4]可以切换动画Animation Clip,[5]为每个动画创建不同的时间线。

动作编辑器

从[4]可以看到,当前添加了两条时间线,可以通过关键帧上下键切换不同的动画,空格键播放动画。

导出fbx

导出fbx

[1]绑定纹理,[3]将blender坐标系转换为浏览器web坐标系。

参考文档

程序控制动画

帧事件

import { Animation, Component, _decorator } from 'cc';
const { ccclass, property } = _decorator;

@ccclass("MyScript")
class MyScript extends Component {  // 需要将该组件绑定到骨骼动画节点上  
    public start() {
        const skeletalAnimation = this.node.getComponent(SkeletalAnimation);
        if (skeletalAnimation && skeletalAnimation .defaultClip) {
            const { defaultClip } = skeletalAnimation ;                        
            defaultClip.events = [ // 添加帧事件
                {
                    frame: 0.5, // 第 0.5 秒时触发事件
                    func: 'onTriggered', // 事件触发时调用的函数名称
                    params: [ 0 ], // 向 `func` 传递的参数
                }
            ];                                         

            skeletalAnimation.clips = skeletalAnimation.clips;                        
        }
    }

    public onTriggered(arg: number) { // 骨骼动画执行到第0.5s触发该函数
        console.log('I am triggered!', arg);
    }
}

自定义动画,可以在动画编辑器面板通过右键添加帧事件:


帧事件

其中:

Notes:

动画事件回调

目前支持的回调事件包括:

import { _decorator, Component, Node, SkeletalAnimation, Animation, SkeletalAnimationState } from 'cc';
const { ccclass, property } = _decorator;

@ccclass('SkeletonAnimationEvent')
export class SkeletonAnimationEvent extends Component {
    start() {

        const skeletalAnimation = this.node.getComponent(SkeletalAnimation); // 获取动画组件
        skeletalAnimation.on(Animation.EventType.FINISHED, this.onAnimationFinished, this); // 绑定事件监听
    }

    onAnimationFinished(type:Animation.EventType, state:SkeletalAnimationState){

    }
}

通信

父子

事件冒泡

// 子节点的组件脚本中
this.node.dispatchEvent( new MyEvent('foobar', true, 'detail info') );
// 父节点的组件脚本中
this.node.on('foobar', (event: MyEvent) => {
  event.propagationStopped = true;
});

Notes

注入对象实例

调用实例节点方法

if(this.playerCtrl){
    // 禁止接收用户操作人物移动指令
    this.playerCtrl.setInputActive(false);
    // 重置人物位置
    this.playerCtrl.node.setPosition(Vec3.ZERO);
}

调用实例组件方法

  const item = instantiate(this.itemPrefab); // 实例化
  const data = this.items[i];
  this.node.addChild(item);
  item.getComponent('ItemTemplate').init(data) // 查找对应组件,调用方法

其中ItemTemplate组件定义:

import { _decorator, Component, Label, Sprite } from "cc";
import { Item } from "./ItemManager";
const { ccclass, property } = _decorator;

@ccclass("ItemTemplate")
export class ItemTemplate extends Component {
  @property
  public id = 0;
  @property(Sprite)
  public icon: Sprite | null = null;
  @property(Label)
  public itemName: Label | null = null;
  @property(Label)
  public itemPrice: Label | null = null;
  init(data: Item) {
    this.id = data.id;
    this.itemName.string = data.itemName;
    this.itemPrice.string = data.itemPrice;
  }
}

事件线程

Cocos Creator 引擎提供了 EventTarget 类,用以实现自定义事件的监听和发射

import { _decorator, Component, EventTarget } from 'cc';
const { ccclass } = _decorator;
const eventTarget = new EventTarget();

@ccclass("Example")
export class Example extends Component {
    onEnable () {
        // 监听事件可以通过 eventTarget.on() 接口来实现
        eventTarget.on('foobar', this._sayHello, this);
    }

    onDisable () {
        // 当我们不再关心某个事件时,我们可以使用 off 接口关闭对应的监听事件。
        eventTarget.off('foobar', this._sayHello, this);
    }

    _sayHello () {
        console.log('Hello World');
    }
}

// 发射事件可以通过 eventTarget.emit() 接口来实现,参数最多只支持 5 个事件参数
eventTarget.emit(type, ...args);

适配

多分辨率适配

可以通过以下几个部分完成多分辨率适配解决方案:

Cocos Creator 提供了两种 Web 平台的页面模板,可以通过 发布平台 的下拉菜单选择 Web Mobile 或 Web Desktop,它们的区别主要在于:

  • Web Mobile 会默认将游戏视图撑满整个浏览器窗口
  • Web Desktop 允许在发布时指定一个游戏视图的分辨率,而且之后游戏视图也不会随着浏览器窗口大小变化而变化。

九宫格格式的图像

如果图像资源是用九宫格的形式生产的,那么不管 Sprite 如何放大,都不会产生模糊或变形。

切分图像

切分图像 资源原图 九宫图

应用图像

Sprite应用

三方库支持

调试

  1. 在 偏好设置 面板中指定了 <u>默认脚本编辑器</u>,便可以在 资源管理器 中双击脚本文件打开代码编辑器快速编辑代码。

  2. Cocos Creator 在顶部菜单栏的 开发者 -> VS Code 工作流 中集成了 添加编译任务 和 添加 Chrome Debug 配置 功能,分别点击可给vs code添加调试任务task

    编译任务
  1. 使用 VS Code 调试网页版游戏

    1. 在 VS Code 中点击左侧栏的 调试 按钮打开调试面板,并在最上方的调试配置中选择 Cocos Creator Launch Chrome against localhost,然后点击左侧绿色的开始按钮进行调试
      调试
2.  更新脚本后,在VS Code 里按下快捷键 Cmd/Ctrl + P,激活 快速打开 输入框,然后输入`task CocosCreator compile`,选择 `CocosCreator compile`,即可在Chrome中查看最新脚本运行。
CocosCreator compile

性能优化

静态资源

在 属性检查器 里设置资源虽然很直观,但资源只能在场景里预先设好,没办法动态切换。

动态加载

动态加载应用包内的本地资源

通常我们会把项目中需要动态加载的资源放在 resources 目录下,配合 resources.load 等接口动态加载。

// 加载 test_assets 目录下所有资源
resources.loadDir("test_assets", function (err, assets) {
    // ...
});

// 加载 test_assets 目录下所有 SpriteFrame,并且获取它们的路径
resources.loadDir("test_assets", SpriteFrame, function (err, assets) {
    // ...
});

动态加载远程资源

直接调用 assetManager.loadRemote 方法

// 远程 url 带图片后缀名
let remoteUrl = "http://unknown.org/someres.png";
assetManager.loadRemote<ImageAsset>(remoteUrl, function (err, imageAsset) {
    const spriteFrame = new SpriteFrame();
    const texture = new Texture2D();
    texture.image = imageAsset;
    spriteFrame.texture = texture;
    // ...
});

// 远程 url 不带图片后缀名,此时必须指定远程图片文件的类型
remoteUrl = "http://unknown.org/emoji?id=124982374";
assetManager.loadRemote<ImageAsset>(remoteUrl, {ext: '.png'}, function (err, imageAsset) {
    const spriteFrame = new SpriteFrame();
    const texture = new Texture2D();
    texture.image = imageAsset;
    spriteFrame.texture = texture;
    // ...
});

动态加载本地设备存储资源

直接调用 assetManager.loadRemote 方法

// 用绝对路径加载设备存储内的资源,比如相册
const absolutePath = "/dara/data/some/path/to/image.png";
assetManager.loadRemote<ImageAsset>(absolutePath, function (err, imageAsset) {
    const spriteFrame = new SpriteFrame();
    const texture = new Texture2D();
    texture.image = imageAsset;
    spriteFrame.texture = texture;
    // ...
});

Notes:

  1. assetManager.loadRemote这种加载方式只支持图片、声音、文本等原生资源类型,不支持 SpriteFrame、SpriteAtlas、TiledMap 等资源的直接加载和解析。

  2. Web 端的远程加载受到浏览器的 <u>CORS 跨域策略限制</u>,如果对方服务器禁止跨域访问,那么会加载失败,而且由于 WebGL 安全策略的限制,即便对方服务器允许 http 请求成功之后也无法渲染。

预加载

场景预加载

director.preloadScene("table", function () {    
  console.log('Next scene preloaded');
});
// 在某个时机调用loadScene
// 就算预加载还没完成,直接调用 director.loadScene,预加载完成后场景就会启动
director.loadScene("table");

动态资源预加载

resources.preload('test_assets/image/spriteFrame', SpriteFrame);

/**
* 开发者可以使用预加载相关接口提前加载资源,
* 不需要等到预加载结束即可使用正常加载接口进行加载,
* 正常加载接口会直接复用预加载过程中已经下载好的内容,缩短加载时间。
*/ 
resources.load('test_assets/image/spriteFrame', SpriteFrame, (err, spriteFrame) => {
    this.node.getComponent(Sprite).spriteFrame = spriteFrame;
});

分包预加载

Asset Bundle 中提供了 preloadpreloadDir 接口用于预加载 Asset Bundle 中的资源,具体的使用方式和 assetManager 一致。

分包

Asset Bundle 作为资源模块化工具,允许开发者按照项目需求将贴图、脚本、场景等资源划分在多个 Asset Bundle 中,然后在游戏运行过程中,按照需求去加载不同的 Asset Bundle,以减少启动时需要加载的资源数量,从而减少首次下载和加载游戏时所需的时间。

Asset Bundle 可以按需求放置在不同地方,比如可以放在远程服务器、本地、或者小游戏平台的分包中。

  1. 自定义 Asset Bundle 是以 文件夹 为单位进行配置的。当我们在 资源管理器 中选中一个文件夹时,属性检查器 中就会出现一个 配置为 Bundle 的选项,勾选开启Bundle分包:


    Bundle分包
  1. 定义配置,点击面板右上方的 绿色打钩按钮,该文件夹就被配置为 Asset Bundle 的打包预设集合了,在放置需要的资源后,然后在 构建发布 面板选择对应的平台进行构建即可得到对应的 Asset Bundle。
    Asset Bundle 配置面板
  1. assetManager.loadBundleAPI传入 Asset Bundle 配置面板中的 Bundle 名称 或者 Asset Bundle 的 url来加载 Asset Bundle
assetManager.loadBundle('01_graphics', (err, bundle) => {
    bundle.load(`prefab`, Prefab, function (err, prefab) {
        let newNode = instantiate(prefab);
        director.getScene().addChild(newNode);
    });
    // 加载 textures 目录下的所有资源
    bundle.loadDir("textures", function (err, assets) {
        // ...
    });

    // 加载 textures 目录下的所有 Texture 资源
    bundle.loadDir("textures", Texture2D, function (err, assets) {
        // ...
    });
});

// 当复用其他项目的 Asset Bundle 时
assetManager.loadBundle('https://othergame.com/remote/01_graphics', (err, bundle) => {
    bundle.load('xxx');
});

Notes:

  1. 释放 Asset Bundle 中的资源

在资源加载完成后,所有的资源都会被临时缓存到 assetManager 中,以避免重复加载。当然,缓存中的资源也会占用内存,有些资源如果不再需要用到,需要进行释放

// 方式一、使用常规的 assetManager.releaseAsset 方法进行释放。
bundle.load(`image/spriteFrame`, SpriteFrame, function (err, spriteFrame) {
    assetManager.releaseAsset(spriteFrame);
});
// 方式二、使用 Asset Bundle 提供的 release 方法,释放在 Asset Bundle 中的单个资源。
bundle.load(`image/spriteFrame`, SpriteFrame, function (err, spriteFrame) {
    bundle.release(`image`, SpriteFrame);
});
// 方式三、使用 Asset Bundle 提供的 releaseAll 方法,释放所有属于该 bundle 的资源
bundle.load(`image/spriteFrame`, SpriteFrame, function (err, spriteFrame) {
    bundle.releaseAll();
});
  1. 移除 Asset Bundle
let bundle = assetManager.getBundle('bundle1');
// 释放在 Asset Bundle 中的单个资源
bundle.release(`image`, SpriteFrame);
assetManager.removeBundle(bundle);

let bundle = assetManager.getBundle('bundle1');
// 释放所有属于 Asset Bundle 的资源
bundle.releaseAll();
assetManager.removeBundle(bundle);

资源释放

资源引用类型:

资源释放类型:

物理系统

物体需要具备完全物理特性的前提条件物体同时具备 刚体 和 碰撞体,并调整好其质心位置和碰撞体的形状。

碰撞体

碰撞组件属性 IsTrigger 决定了组件为触发器还是碰撞器。

刚体

碰撞体间定义碰撞发生的可能性是通过刚体的 Group 属性,而非 Node 的 Layer 属性。

刚体类型

物理材质

物理材质是一种资源,它记录了物体的物理属性,这些信息用来计算碰撞物体受到的摩擦力和弹力等。

物理事件

真实世界碰撞效果

    protected shoot(velocity: number) {
        // 获取炮弹
        const bulletNode = this.generateBullet(),
            bulletRigidBody = bulletNode.getComponent(RigidBody);
        // 方向和速度(默认前方为 -z 方向,需要反过来)
        const direction = bulletNode.forward.negative();
        direction.multiplyScalar(velocity);
        // 给刚体设置速度
        bulletRigidBody.setLinearVelocity(direction);
    }

Notes:

射线检测

射线检测是对一条射线和非动力学刚体碰撞组件进行相交性判断

检测对象需要满足:

// bullet物理引擎测试结果:
const worldRay = new geometry.Ray(0, -1, 0, 0, 1, 0); // 世界坐标下的射线
// 以下参数可选
const mask = 0xffffffff;
const maxDistance = 10000000;
const queryTrigger = true;

const rayCollision = PhysicsSystem.instance.raycast(worldRay, mask, maxDistance, queryTrigger);
if(rayCollision){
    const results = PhysicsSystem.instance.raycastResults;
    for (let i = 0; i < results.length; i++) {
        const result = results[i];
        const collider = result.collider;
        const distance = result.distance;
        const hitPoint = result.hitPoint;
        const hitNormal = result.hitNormal;
    }
}

Notes:

粒子系统

  1. 添加3D粒子系统


    创建3D粒子系统
    • 在[1]层级管理器中右键[2]创建特效 —> 粒子系统[3]
  2. 添加粒子材质


    粒子材质
  1. 处理贴图

使用Photoshop等DCC设计工具去除素材的颜色,仅保留明度的信息:

  1. 配置粒子贴图


    粒子贴图
    • 资源管理器中选中创建的粒子材质,通过属性检查器[1]配置材质属性;

    • 粒子属性Effect设定为particles/builtin-particle;

    • 展开[4]配置表,将贴图资源拖拽到Main Texture,将材质贴图;

Good to know:

  1. 粒子渲染贴图


    渲染贴图
    • 层级管理器中选中添加的粒子系统,在属性检查器[1]配置渲染贴图;

    • 展开[2]粒子渲染器配置表,将粒子材质拖拽到Cpu Material[4];

文件模板

自定义html构建模板

创建html构建模板
修改index.ejs模板
  1. cocos creator编辑器中添加构建模版;

  2. 在代码编辑器中修改index.ejs模板;

  3. build-templates/web-desktop目录下的资源会自动打包到build目录中

    • build-templates/web-desktop放置ico图标可以用于修改favicon.ico

构建模板更多详见

脚本模板

.creator/asset-template/typescript/CustomComponent添加脚本模板:

import { _decorator, Component, Node } from 'cc';
const { ccclass, property } = _decorator;

/**
 * 
 * <%UnderscoreCaseClassName%>
 * <%CamelCaseClassName%>
 * <%Author%>
 * <%DateTime%>
 * <%FileBasename%>
 * <%FileBasenameNoExtension%>
 * <%URL%>
 * <%ManualUrl%>
 *
 */

@ccclass('Robot<%CamelCaseClassName%>')
export class Robot<%CamelCaseClassName%> extends Component {
    start() {

    }

    update(deltaTime: number) {

    }
}

脚本模板更多详见

打包

构建支持平台

平台 平台构建插件名 支持的特殊文件类型
华为 AGC huawei-agc 暂不支持
支付宝小游戏 alipay-mini-game game.json
字节跳动小游戏 bytedance-mini-game game.ejs、game.json、project.config.json
OPPO 小游戏 oppo-mini-game manifest.json
华为快游戏 huawei-quick-game 暂不支持
Cocos Play cocos-play game.config.json
vivo 小游戏 vivo-mini-game project.config.json
小米快游戏 xiaomi-quick-game manifest.json
百度小游戏 baidu-mini-game game.json、project.swan.json
微信小游戏 wechatgame game.ejs、game.json、project.config.json
Web Desktop web-desktop index.ejs
Web Mobile web-mobile index.ejs
原生平台 native 暂不支持
支持平台

打包

在[1]项目菜单中选择[2]构建发布


构建发布

自定义插屏

场景初始化加载预览图片

插屏配置

社区

引擎对比

基本情况 Three.js Unity3D Cocos Creator
定位 轻量级3D库 游戏开发引擎 轻量级游戏开发引擎
二次开发语言 Javascript开发 需安装Unity编辑器,C#语言开发 需安装Cocos Creator编辑器,Typescript开发
模型来源 三方提供,手动维护 三方提供,手动维护 三方提供,手动维护
辅助器 提供了各种辅助工具,如射线辅助线、坐标辅助线 提供了部分辅助工具,如射线辅助线 没有辅助工具,需要自己通过现有资源模拟

小技巧

通过常驻节点进行场景资源管理和参数传递

引擎同时只会运行一个场景,当切换场景时,默认会将场景内所有节点和其他实例销毁。如果我们需要用一个组件控制所有场景的加载,或在场景之间传递参数数据,就需要将该组件所在节点标记为「常驻节点」,使它在场景切换时不被自动销毁,常驻内存。

// 添加一个节点的常驻属性:
director.addPersistRootNode(myNode);
// 要取消一个节点的常驻属性:
director.removePersistRootNode(myNode);

Notes:

Blender使用mixamo处理骨骼动画

  1. github中直接通过zip包下载源码

  2. 在[编辑]菜单中选择[偏好设置]


    偏好设置
  3. 在[偏好设置]面板中选择[插件]。

  4. 在[2]选择zip安装包进行安装,安装完成后,可在[3][4]的检索的基础上看到mixamo列表项。

  5. 勾选[5]开启mixamo插件。

    mixamo插件安装应用
  1. mixamo开启插件设置
    mixamo插件应用

预览看不到地形的贴图

仅仅需要在cocos编辑器中保存一下即可。

概念

引擎:

  1. 内置完整的工具集,而非生态扩展

  2. 特定领域,而非通用

  3. 专门性

运行时:

  1. 可以是通用的(如语言运行时)或特定功能的(如游戏引擎运行时)

  2. 包括解释器,解释和执行代码

Node vs. Component

Node:

Component:

Prefab(预制)资源

Prefab(预制)资源,作为我们动态生成节点时使用的模板。

cc类

装饰器 ccclass 应用在类上时,此类称为 cc 类。

  • 未声明 ccclass 的组件类,也无法作为组件添加到节点上。
  • ccclass 装饰器的参数 name 指定了 cc 类的名称,cc 类名是 独一无二 的,这意味着即便在不同目录下的同名类也是不允许的。
  • 类名不应该以 cc.internal. 作为前缀,这是 Cocos Creator 的保留类名前缀。

组件类装饰器

ccclass装饰器 修饰,且继承 Component 的子类,此类称为 cc 组件类。

executeInEditMode:动态加载的预制体

import {
  _decorator,
  Component
} from "cc";
const { ccclass, property, executeInEditMode } = _decorator;

@ccclass("GameManager")
@executeInEditMode
export class GameManager extends Component {

}

默认在层级管理器和场景管理器中看不到动态加载的预制体或者动态创建的节点 new Node(),可以通过[@executeInEditMode装饰器](https://docs.cocos.com/creator/3.8/api/en/function/_decorator.executeInEditMode)使继承自组件的ccclass在编辑模式下执行。

Notes:

更多内容详见

executionOrder:生命周期回调的执行优先级

小于 0 的脚本将优先执行,大于 0 的脚本将最后执行。排序方式如下:

可以通过组件类装饰器executionOrder 用来指定脚本生命周期回调的执行优先级。

const { ccclass, executionOrder } = _decorator;

@ccclass('Example')
@executionOrder(3)
export class Example extends Component {
}

属性装饰器

在编辑器 属性检查器 中展示的属性,属性名开头不应该带 _,否则会识别为 private 属性,private 属性不会在编辑器组件属性面板上显示

属性装饰器参数详见

基础属性类型

CCIntegerCCFloatCCBooleanCCStringCocos Creator基础属性类型标识

group分组

当脚本中定义的属性过多且杂时,可通过 group 对属性进行分组、排序,方便管理。同时还支持对组内属性进行分类。

group 写法包括以下两种:

上一篇 下一篇

猜你喜欢

热点阅读