最近在学习cocos,但是概念太多,记不住,实在是记不住,那就只能照着别人的demo来敲了。
下面就记录一下学到的一些东西。
物体的移动以及鼠标事件,键盘事件,以及声音播放,动态切换图片,等等。。。直接上demo把
keyboard.ts // Learn TypeScript: // - https://docs.cocos.com/creator/manual/en/scripting/typescript.html // Learn Attribute: // - https://docs.cocos.com/creator/manual/en/scripting/reference/attributes.html // Learn life-cycle callbacks: // - https://docs.cocos.com/creator/manual/en/scripting/life-cycle-callbacks.html const {ccclass, property} = cc._decorator; @ccclass export default class NewClass extends cc.Component { @property(cc.Label) label: cc.Label = null; @property(cc.AudioClip) audio:cc.AudioClip=null; @property(cc.SpriteFrame) face1:cc.SpriteFrame=null; @property(cc.SpriteFrame) face2:cc.SpriteFrame=null; @property faceLeft:boolean=false // LIFE-CYCLE CALLBACKS: onLoad () { cc.systemEvent.on('keydown',this.keyBoardHandle,this); } start () { } keyBoardHandle(e:cc.Event.EventKeyboard){ cc.log(e,e.keyCode,cc.macro.KEY) if(e.keyCode===cc.macro.KEY.left){ this.move(1) }else if(e.keyCode===cc.macro.KEY.right){ this.move(2) } } move(direct:number){ switch(direct){ case 1: this.node.x-=10; this.faceLeft=true break; case 2: this.node.x+=10; this.faceLeft=false break; } this.changeFace() //播放音乐 if(this.audio){ cc.audioEngine.play(this.audio,false,4) } } changeFace(){ let sprite:cc.Sprite=this.node.getComponent(cc.Sprite); if(this.faceLeft){ sprite.spriteFrame=this.face1; }else{ sprite.spriteFrame=this.face2; } } // update (dt) {} }
click.ts // Learn TypeScript: // - https://docs.cocos.com/creator/manual/en/scripting/typescript.html // Learn Attribute: // - https://docs.cocos.com/creator/manual/en/scripting/reference/attributes.html // Learn life-cycle callbacks: // - https://docs.cocos.com/creator/manual/en/scripting/life-cycle-callbacks.html const {ccclass, property} = cc._decorator; @ccclass export default class NewClass extends cc.Component { // @property(cc.Label) // label: cc.Label = null; @property() toLeft: boolean = true; @property step:number=0; //音乐资源 // @property(cc.AudioClip) // audio:cc.AudioClip=null; // LIFE-CYCLE CALLBACKS: onLoad () { this.node.on('mousedown',this.clickHandle,this); } start () { } clickHandle(){ //点击按钮,小人运动 //1,先找到佩奇 let pig=cc.find('Canvas/佩奇');
//这里需要说明一下,这里就是找到另外的脚本,然后下面运营另外脚本里的方法,就和引入js然后执行里面的方法差不多 let script=pig.getComponent('KeyBoard') if(this.toLeft){ // pig.x-=10; script.move(1) }else{ // pig.x+=10; script.move(2) } //播放音乐 // if(this.audio){ // cc.audioEngine.play(this.audio,false,4) // } } // update (dt) {} }
上面就是一个很简单的例子,通过鼠标点击左右按钮或者按键盘来操作佩奇左右运动并且有音效的小栗子。