Cocos Creator 入门

Cocos Createor

资源

场景

  1. 节点树
  2. 节点与组件
  3. 坐标系

脚本

  1. 组件声明,生命周期回调
var Component = cc.Class({
    // 用于序列化,可省略
    name: 'some Name', 
    // 构造函数
    cotr: function() {
        // 不会覆盖父类的构造函数,自动调用父类构造方法
        cc.log(this instanceof Component);
    },
    // 继承
    extends: cc.Component,
    // 属性声明,可在编辑器<属性检查其>中可视化编辑。需声明类型
    properties: {
        id: 20, // value
        target: cc.Node, // constructor
        pos: new cc.Vec2(10, 20),  // obj
        frames: [cc.SpriteFrame], // array
        // 完整声明
        score: {
            default: 0,
            displayName: "<属性检查器>标签名",
            tooltip: "<属性检查器>提示",
            visible: true,
            serializable: true, // false不可序列化(保存)
            type: cc.Label,
        }
    },

    // LIFE-CYCLE CALLBACKS:
    onLoad: function() {
        cc.log("All nodes loaded..");
    },
    start: function() {
        cc.log("All component loaded.");
    },
    update: function() {
        cc.log("request frame.");
    },
    lateUpdate: function() {
        cc.log("After frame update.");
    },
    onDestory: function() {
        cc.log("will be destoried.");
    },
    onEnable: function() {
        cc.log("activate");
    },
    onDisable: function() {
        cc.log("disabled.");
    },
});
  1. 节点访问
    • 直接创建

      var node = new cc.Node('Sprite');
    • 克隆已有节点

      var node = cc.instantiate(this.someNodeTarget);
    • 创建预制

      var node = cc.instantiate(this.somePrefab);
    • 销毁节点

      someNode.destory();
      removeFromParent()只是从父节点移除(可能移动到其他节点下面),不会释放内存
    • 访问组件/节点

      cc.Node.getComponent(); // 访问组件
      cc.Node.prop = cc.Node node; // 属性引用
      cc.node.children; // 访问子节点
      cc.node.getChildByName(); // 子查找
      cc.Node.find(path, [root]); // 绝对/相对路径查找
    • 全局模块

      // Global.js
      module.exports = {foo: null, bar: null};
      // somewhere
      Global.foo = this.node;
      Global.bar = this.getComponent(cc.Label);
  2. 场景加载
    • 直接加载

      cc.director.loadScene("MyScene");
    • 加载回调

      cc.director.loadScene("MyScene", onSceneLaunched);
      onSceneLaunched: function() {
          cc.game.addPersistRootNode(myNode); // 设置常驻节点,用以在不同场景间保留公共数据(角色信息等。。)
      }
    • 预加载

      cc.director.preloadSence("senceName", cbFn);
      cc.director.loadScene("sceneName");//后台静默加载,需要手动切换
  3. 资源加载
    • 资源可以作为属性进行设置,也可动态加载
    • 动态加载资源必须放在assets/resources及其子文件夹下面
    • 资源的释放需注意依赖关系
    cc.loader.loadRes(path, cc.Type, cbFn); // 指定类型加载
    
    cc.loader.loadResDir(dir, cbFn); // 批量加载文件夹
    
    cc.loader.load(remoteUrl, cbFn); // 加载远程资源(仅图片,声音,文本),受跨域策略限制
    
    cc.loader.release(texture);// 直接释放单个资源(无依赖关系)
    
    // 释放预制(包含其他依赖)以及它所依赖的资源
    var deps = cc.loader.getDependsRecursively(prefab); // 获取其依赖的资源
    var idx = deps.indexOf(extra._uuid); // 查找不想释放的依赖资源
    index != -1 && deps.splice(idx, 1); // 从集合中移除
    cc.loader.release(deps);// 释放所有依赖资源
  4. 事件监听
    • 系统内置事件
    • 自定义事件
      • emit(event, args) 仅节点内
      • dispatchEvent(cc.Event.EventCustom(event, args)) 通过节点树冒泡传递,可通过event.stopPropagation()停止冒泡
  5. 动作/动画
    • 基本动作 https://docs.cocos.com/creator/manual/zh/scripting/action-list.html
      • moveTo(duration, cc.V2)
      • moveBy(duration, cc.V2)
      • scaleTo(duration, times)
      • skewTo(duration, angle)
      • rotateTo(duration, angle)
      • ...
    • 播放动作

      var act1 = cc.spawn(part1, part2); // 同步动作
      var act2 = act1.speed(2); // 与act1相同的动作,但以2倍速度播放
      var cbFn = cc.callFunc(func, root, args);
      var act3 = cc.repeat(act2); // 重复动作act3 
      var act4 = cc.sequence(act1, cbFn, act2, act3); // 顺序动作/回调
      var action = cc.repeatForever(act4); // 循环重复 
      cc.node.runAction(action); // 执行动作
    • cc.tween
      cc.Action的再封装,链式调用更加简洁易用。

      扫描二维码关注公众号,回复: 5960551 查看本文章
      cc.tween(node)
          .to(duration, {scale: x, moveTo: y}) // 相当于 cc.spawn(cc.scale(x), cc.moveTo(y))
          .by(duration, {scale: x, moveTo: y}) // 同上
          .to(duration, action, {easing: 'sineOutIn'}) // 同时制定缓动函数
          .parallel(
              cc.tween().to(1, action),
              cc.tween().to(2, action), // 同步执行两个 cc.tween
          )
          .call( () => {console.log("callback function.")} ) // 插入回调
          .then(cc.tween().to()) // 嵌套组合
          .repeat(times) // 重复以上所有动作
          .delay(sec) // 延迟执行
          .repeat(times, cc.tween()) // 仅重复这个动作
          .start()
  6. 高级应用
    • 执行顺序
      • 手动控制。通过自定义load,update方法,统一控制

        // Game.js
        const Player = require('Player');
        const Enemy = require('Enemy');
        const Menu = require('Menu');
        cc.Class({
            properties: {
                player: Player,
                enemy: Enemy,
                menu: Menu,
            },
            onLoad: function() {
                this.player.init();
                this.enemy.init();
                this.menu.init();
            },
            update: function(dt) {
                this.player.updatePlayer(dt);
                this.enemy.updateEnemy(dt);
                this.menu.updateMenu(dt);
            }
        })
      • executionOrder

      cc.Class({
          editor: {
              executionOrder: -1 // 默认值0,值越小优先级越高
          }
      });
    • 网络请求
      • XMLHttpRequest (Ajax)
      • WebSocket
    • 对象池 cc.NodePool
      • 减少资源的重复创建与销毁
      • 循环利用的大量Prefab
      • unuse()reuse() ?

猜你喜欢

转载自www.cnblogs.com/dapianzi/p/10743572.html