如何僅用一張圖片就能實現【炫光方塊】特效?

  • 2019 年 10 月 7 日
  • 筆記

摘要

CocosCreator 的節點上的顏色屬性對 3D 模型是不起作用的,要想修改模型顏色就要對材質操作,而材質是基於 effect 渲染的。那麼怎麼改變模型顏色呢?

正文

看看效果

素材製作

打開 Photoshop 軟體,我們新建一個 200 * 200 的畫布。

然後填充黑色,加白色漸變的邊。複製,旋轉到四邊。

好了,最終圖片。

內置effect

讓我們新建工程,場景。在資源管理器新建一個材質,選擇 builtin-unlit (無需光照)並拖入素材。

Canvas 下新建一個 3D 物體 New Box。設置材質,綁上腳本。

改變顏色腳本

box.js

cc.Class({      extends: cc.Component,        properties: {      },        onLoad () {          // 獲得組件          this.m = this.getComponent(cc.MeshRenderer);          // 定義初始顏色          this.color = {              r: 100,              g: 0,              b: 0          };          // rgb顏色緩動          cc.tween(this.color)              .repeatForever(                  cc.tween()                  .to(0.8, {r: 255, g: 0, b: 0})                  .to(0.8, {r: 0, g: 100, b: 0})                  .to(0.8, {r: 0, g: 255, b: 0})                  .to(0.8, {r: 0, g: 0, b: 100})                  .to(0.8, {r: 0, g: 0, b: 255})                  .to(0.8, {r: 100, g: 0, b: 0})              )              .start();      },        setColor () {          let color = cc.color(this.color.r, this.color.g, this.color.b, 255);          // 修改材質的屬性          this.m.sharedMaterials[0].setProperty('diffuseColor', color);      },        update (dt) {          this.setColor();      }    });

好了,我們可以開心的把它拖成預製體了。

管理腳本

層級管理器,注意 boxMgr 空節點要轉為 3D。

在 Canvas 節點上綁定腳本。通過腳本初始化很長的路,然後在 update 里模擬前進運動。main.js

cc.Class({      extends: cc.Component,        properties: {          mgr: cc.Node,          box: cc.Prefab      },        onLoad () {          this.init();      },        init () {          for (let i = -1; i <= 1; i++) {              for (let j = -60; j <= 10; j++) {                  let b = cc.instantiate(this.box);                  this.mgr.addChild(b);                  b.x = 110 * i;                  b.z = 150 * j;                  b.y = -50;              }          }      },        update (dt) {          this.mgr.z += 500 * dt;          if (this.mgr.z > 300) {              this.mgr.z = 0;          }      }    });

攝像機調整

最後不要忘記了攝像機要切換為 3D 攝像機。設置下投影方式,然後調節下 z 軸位置為 800。

結語

effect,材質的引入將使得遊戲特效製作更加方便。

CocosCreator v2.1.2 的 3D 模型合批還不支援。DC 較高。CocosCreator v2.1.3 和 v2.2.0 應該能解決這個問題。