Cocos Creator支持JS和TS两种脚本,在这里我强烈建议使用TS来做脚本开发。有几个比较重要的原因:
- TS本身是JS的超集,完全兼容js
- TS有静态语言特性,代码易于阅读和维护
- 近乎完美的智能提示,而JS的代码提示几乎没有
在Creator里面写TS,要实现代码智能提示,需要手动添加申明文件,步骤如下:
点击菜单 开发者->VS Code 工作流->更新VS Code智能提示数据。
点这个菜单,实际上就是把引擎目录下的模板文件creator.d.ts拷贝到了你的项目目录下,这个模板文件是引擎开发组写好了放在引擎目录下的,每个版本都有对应的实现。
在Creator的新版本预发布的阶段,通常这个声明文件很不完善,这就导致很多接口提示没有,写代码就会爆红,对于有强迫症的同学来说,可能总是会想办法把爆红的提示去掉。
找到引擎安装目录,打开文件夹resources\utils\api
,可以看到有一个creator.d.ts文件,这个文件就是操作Creator编辑器的时候拷贝到项目目录下的。我们只要修改了这个文件,所有项目都可以更新。
修改智能提示有两种方式,一种是修改引擎的creator.d.ts,另一种是自己新建一个自己的声明文件,例如我的捕鱼里面就是自己定义了一个global.d.ts。
在1.93版本的时候,我把shader相关的隐藏接口全部写在这个声明文件里面,代码如下
declare module cc {
/**
* 实现WebGL program的类,用来做shader编程
*/
export class GLProgram{
/**
* 实现WebGL program的类,用来做shader编程
*/
constructor();
/**
* 使用顶点shader字符串和片段shader字符串初始化cc.GLProgram
* @param vertShaderStr 顶点shader字符串
* @param fragShaderStr 片段shader字符串
*/
initWithString(vertShaderStr: string, fragShaderStr: string): boolean;
/**
* It will add a new attribute to the shader
* @param attributeName
* @param index
*/
addAttribute(attributeName: number, index: number);
/**
* Initializes the cc.GLProgram with a vertex and fragment with string
* @param vertShaderStr
* @param fragShaderStr
*/
initWithVertexShaderByteArray(vertShaderStr: string, fragShaderStr: string):boolean;
/**
* 连接 glprogram
*/
link(): boolean;
/**
* 这个函数创建4个统一变量即uniform
* cc.macro.UNIFORM_PMATRIX
* cc.macro.UNIFORM_MVMATRIX
* cc.macro.UNIFORM_MVPMATRIX
* cc.macro.UNIFORM_SAMPLER
*/
updateUniforms();
/**
* it will call gl.useProgram()
*/
use();
/**
* calls retrieves the named uniform location for this shader program.
* @param name
*/
getUniformLocationForName(name: string): number;
/**
* calls glUniform1f only if the values are different than the previous call for this same shader program.
* @param location
* @param f1
*/
setUniformLocationWith1f(location, f1);
/**
* calls glUniform2f only if the values are different than the previous call for this same shader program.
* @param location
* @param f1
* @param f2
*/
setUniformLocationWith2f(location,f1,f2)
}
export class GLProgramState{
static getOrCreateWithGLProgram(program:GLProgram):any;
}
}
写法也很简单,在Cocos Creator中,基本上都是基于模块和命名空间的,基本没有单独的变量声明。使用关键字declare
来声明即可。
同名的变量会被无冲突合并,这样是为什么我在项目里面定义一个global.d.ts,在里面声明了cc这个命名空间,没有和creator.d.ts里面的声明冲突的原因。
新版的Cocos Creator有很多声明缺失,比如2.1.1里面关于3d和材质的代码,基本上没有提示。
后面我将会更新一版2.1.1的智能提示文件,方便大家开发。
捕鱼代码
https://github.com/fylz1125/CCFish
关注我的微信
扫码关注我的微信【Cocos Creator研究笔记】,每天更新。