TypeScript在CocosCreater中的应用
与JavaScript的联系
- TypeScript , 强类型的 JavaScript ,可以编译为纯JavaScript
- :链接: TS的手册.
- 使用TS的原因:JS没有类型标识,编辑器无法精确的提示,为方便书写,使用TS。同时TS支持JS的大部分语法,只是注意变量定义、方法返回的特性等即可。TypeScript的语法比较庞杂,无需深究
使用时要注意的语法
- 变量定义
JS:
var str = "shaofa";
var a = 10;
var node = this.node;
TS:
let str : string = "shaofa";
let a : number = 10;
let node : cc.Node = this.node;
- 方法的参数
JS
moveLeft ( evt ) {
}
TS
moveLeft( evt : cc.Event.EventMouse ) {
}
- 方法的返回值
JS
sum (x, y) {
return x + y;
}
TS
sum (x:number, y:number) :number {
return x + y;
}
使用时大部分的区别,加上类型的声明就行了,让VSCode能够根据类型提示,不需要使用深入特性。
属性的定义
@property("string")
time : string = "";
其中,@property称为装饰器 ( 同Java中的注解语法)
定义规则:
- 若无 @property注解,则不会出现在Cocos Creator属性面板
- @property中,应该指明类型
@property(“string”)
@property(cc.Node) - 基本类型,可以不指定类型
string , number , boolean , bigint - TypeScript里有 number 和 Number 两种类型:number算是基本类型、Number算是引用类型 ( 对象 )
属性的应用
属性的分类:
- 基本类型
string , number, boolean, bigint
注意是number没有细分
- 引用类型
cc.Node 节点
cc.SpriteFrame 图片帧资源
cc.AudioClip 音频资源
基本类型的应用:
const {ccclass, property} = cc._decorator;
@ccclass
export default class NewClass extends cc.Component {
@property
step: number = 20;
@property
towardsLeft: boolean = true;
// LIFE-CYCLE CALLBACKS:
onLoad () {
}
start () {
this.node.on('mousedown', this.move, this);
}
move (evt :cc.Event.EventMouse ){
if(this.towardsLeft)
{
this.node.x -= this.step; // 向左走
}
else
{
this.node.x += this.step; // 向右走
}
}
// update (dt) {}
}
注:
1 . 一个脚本,可以重复使用,应用于多个节点
2. 脚本组件的属性,可以在属性面板里指定初始值
引用类型属性的应用:
const {ccclass, property} = cc._decorator;
@ccclass
export default class NewClass extends cc.Component {
@property
step: number = 20;
@property
towardsLeft: boolean = true;
@property(cc.AudioClip)
audio: cc.AudioClip = null;
// LIFE-CYCLE CALLBACKS:
onLoad () {
}
start () {
this.node.on('mousedown', this.move, this);
}
move (evt :cc.Event.EventMouse ){
if(this.towardsLeft)
{
this.node.x -= this.step; // 向左走
}
else
{
this.node.x += this.step; // 向右走
}
if(this.audio != null)
{
cc.audioEngine.play(this.audio, false, 1);
}
}
// update (dt) {}
}
play(clip,loop,volume)方法参数:
clip: AudioClip The audio clip to play.
loop :Boolean Whether the music loop or not.
volume :Number Volume size.
实现了点击图标运动时的音效播放