目录
1.visualcode---配置model快捷模版
2.定义在属性面板显示的变量
3.获取脚本挂载物体组件
4.删除已挂载的脚本,还得在挂载物体上删除引用。
5.代码发生变动,如新增公有变量。需手动切换鼠标选中物体,再选回来才会刷新。
6.定义的公有物体变量node 没有坐标属性,需进行类型转换
7.Laya脚本参数说明
8.Laya事件广播与接收
9.插值
10.勾股定理 求距离
11.随机值封装
12.获取键盘按键
13.代码获取游戏内物体
14.音乐音效播放
15.按钮点击事件监听
16.游戏暂停、场景跳转与重新加载
17.本地存储 相当于unity的PlayerPrefes
18.延时执行
19.设置游戏画面左右居中
20.碰撞检测,多预制体共用lable标签
21.指定时间间隔循环调用
22.预制体加载与生成
23.对象池的获取与回收
24.使用自定义字体
25.音乐音效一键静音
26.时间轴动画---多状态切换
27.tween动画
28.Dialog弹窗
29.判断所在平台
30.数组
31.判断游戏是否在前台 ----防止游戏进入后台后update方法一直执行
32.监听游戏是否失焦
1.visualcode---配置model快捷模版
code---首选项---配置用户代码片段
//例: { "creat Class":{ "scope": "javascript,typescript", "prefix": "class", "body": [ "/", "*", "* @ author:xxx", "* @ email:@.com", "* @ data: $CURRENT_YEAR-$CURRENT_MONTH-$CURRENT_DATE $CURRENT_HOUR:$CURRENT_MINUTE", "*/", "export default class $TM_FILENAME_BASE extends Laya.Script {", "", "\tconstructor() {", "\t\tsuper();", "\t}", "\t\t/ @prop {name:xxx, tips:\"面板物体\", type:Node, default:null}*/", "\t\t xxx=null;", "", "\tonAwake() {", "\t}", "}" ], "description": "快速创建一个Laya模板类" } }
讯享网
2.定义在属性面板显示的变量
讯享网 / @prop {name:intType, tips:"整数类型示例", type:Int, default:1000}*/ public intType: number = 1000; / @prop {name:numType, tips:"数字类型示例", type:Number, default:1000}*/ public numType: number = 1000; / @prop {name:strType, tips:"字符串类型示例", type:String, default:"hello laya"}*/ public strType: string = "hello laya"; / @prop {name:boolType, tips:"布尔类型示例", type:Bool, default:true}*/ public boolType: boolean = true; / @prop {name:shoe,tips:"物体",type:Node,default:null}*/ public shoe = null; // 更多参数说明请访问: https://ldc2.layabox.com/doc/?nav=zh-as-2-4-0
3.获取脚本挂载物体组件
this.owner.getComponent(Laya.RigiBody);
4.删除已挂载的脚本,还得在挂载物体上删除引用。
5.代码发生变动,如新增公有变量。需手动切换鼠标选中物体,再选回来才会刷新。
6.定义的公有物体变量node 没有坐标属性,需进行类型转换
讯享网2d: public get gameObject():Laya.Sprite { return this.owner as Laya.Sprite; } 3d: public get gameObject():Laya.Sprite3D { return this.owner as Laya.Sprite3D; } ------------------------------------------------- public get transform():Laya.Transform { return this.gameObject.transform; }
7.Laya脚本参数说明
laya脚本参数
8.Laya事件广播与接收
广播事件:
Laya.stage.event("事件名");
接收事件:
讯享网onAwake() { //添加监听 Laya.stage.on("事件名",this,this.reset); } private reset(){ //..... } onDestroy(){ //移除监听 Laya.stage.off("事件名",this,this.reset); }
9.插值
Laya.MathUtill.lerp(curObj.x,targetObj.x,Laya.timer.delta/1000 * speed);
10.勾股定理 求距离
讯享网a*a + b*b = c*c; c = Math.sqrt(a*a + b*b);
11.随机值封装
//随机数封装 getRandom(min,max){ let min = Number(_min); let max = Number(_max); let value = 0; if(max>min){ value = Math.random()*(max-min); value = Math.round(value) +min ; }else{ value = Math.random()*(min-max); value = Math.round(value) +max ; } return value; }
12.获取键盘按键
讯享网1. onUpdate() { if (Laya.KeyBoardManager.hasKeyDown(Laya.Keyboard.A)) { this.rig.setVelocity({ x: -10, y: this.rig.linearVelocity.y }); } else if (Laya.KeyBoardManager.hasKeyDown(Laya.Keyboard.D)) { this.rig.setVelocity({ x: 10, y: this.rig.linearVelocity.y }); } } 2. onKeyDown(e) { //console.log(e.nativeEvent.key+".........2"); if (e.nativeEvent.key == " " && this.canJump) { this.canJump = false; this.rig.setVelocity({ x: this.rig.linearVelocity.x, y: -13 }); } } 3. onKeyPress(e) { console.log(e.nativeEvent.key+".........1"); if(e.nativeEvent.key == "a") { } }
13.代码获取游戏内物体
//查找一级物体 Laya.stage.getChildByName("Player"); 或 this.owner.parent.getChildByName("wuti"); //查找本物体下的子物体 this.owner.getChildByName("子物体名");
14.音乐音效播放
讯享网//播放音乐 Laya.soundManager.playMusic(“地址/music.mp3”,0); //0为无限循环 //单纯播放音效 Laya.SoundManager.playSound("sound/BallHit-01.mp3"); //播放完成后加事件 Laya.SoundManager.playSound("sound/startWistle.mp3",1, new Laya.Handler(this,()=>{ Laya.stage.event("StartGame"); //广播--开始游戏 }));
15.按钮点击事件监听
onAwake() { this.gameOverPanel.getChildByName("btn_menu").on (Laya.Event.CLICK,this,()=>{ //。。。。。 }); }
16.游戏暂停、场景跳转与重新加载
讯享网//跳转场景 this.pausePanel.getChildByName("btn_menu").on(Laya.Event.CLICK,this, ()=>{ Laya.Scene.open("Menu.json"); }); //继续游戏 this.pausePanel.getChildByName("btn_continue").on(Laya.Event.CLICK,this, ()=>{ this.pausePanel.visible = false; this.isPause = false; Laya.timer.scale =1; }); //重新开始 this.pausePanel.getChildByName("btn_restart").on(Laya.Event.CLICK,this, ()=>{ Laya.Scene.open("Main.scene"); }); /游戏暂停 this.owner.parent.getChildByName("btn_pause").on(Laya.Event.CLICK,this, ()=>{ this.isPause = true; this.pausePanel.visible = true; Laya.timer.scale = 0; });
17.本地存储 相当于unity的PlayerPrefes
onEnable(): void { if(Laya.LocalStorage.getItem("headIndex")=="NaN"){ Laya.LocalStorage.setItem("headIndex","1"); } this.head_index = parseInt(Laya.LocalStorage.getItem("headIndex")); this.skinUrl = "Textures/Players/Player-Head-0"+this.head_index+"-n.png"; this.roleIcon.skin = this.skinUrl; }
18.延时执行
讯享网//清除此脚本已存在的timer事件 Laya.timer.clearAll(this); //延迟0.5秒执行 Laya.timer.once(500, this, () => { this.heroIcon.texture = "Textures/Players/Player-Head-01-n.png"; });
19.设置游戏画面左右居中
//场景分辨率 1920*1080 Laya.stage.pivot(960, 0); Laya.stage.x = Laya.stage.width / 2;
20.碰撞检测,多预制体共用lable标签
选中物体下的collider组件,给lable属性命名,后续即可使用lable名判定碰撞物体 
21.指定时间间隔循环调用
讯享网onAwake() { this.ranTime = this.getRandom(300,800); Laya.timer.loop(this.ranTime,this,()=>{ this.carSpawn(); this.ranTime = this.getRandom(300,800); }); }
22.预制体加载与生成
//预制体 carFab = []; //预制体加载地址 carInfo = []; //预制体存放路径 carPath = [ "prefab/car_1.json", "prefab/car_2.json", "prefab/car_3.json", "prefab/car_4.json", "prefab/car_5.json", "prefab/car_6.json", ]; onAwake() { this.loadCarPrefab(); } private loadCarPrefab(){ //获取预制体加载信息 for(let i=0;i<this.carPath.length;i++){ this.carInfo.push({url:this.carPath[i],type:Laya.Loader.PREFAB}); } //进行加载 Laya.loader.load(this.carInfo,Laya.Handler.create(this,(ret)=>{ if(ret){ //加载完成,获取预制体 for(let i=0;i<this.carPath.length;i++){ this.carFab.push(Laya.loader.getRes(this.carPath[i])); } //生成 this.ranTime = this.getRandom(300,800); Laya.timer.loop(this.ranTime,this,()=>{ this.carSpawn(); this.ranTime = this.getRandom(300,800); }); } })); } private carSpawn() { this.carInitX = this.initArray[this.getRandom(0, this.initArray.length - 1)]; let carIndex = this.getRandom(0, this.carPath.length-1); //使用对象池获取对象 let car = Laya.Pool.getItemByCreateFun(carIndex.toString(),()=>{ return this.carFab[carIndex].create(); },this); Laya.stage.addChild(car); car.pos(this.carInitX, this.carInitY); }
23.对象池的获取与回收
讯享网//GameManager.ts private carSpawn() { this.carInitX = this.initArray[this.getRandom(0, this.initArray.length - 1)]; let carIndex = this.getRandom(0, this.carPath.length-1); //使用对象池获取对象 let car = Laya.Pool.getItemByCreateFun(carIndex.toString(),()=>{ return this.carFab[carIndex].create(); },this); Laya.stage.addChild(car); car.pos(this.carInitX, this.carInitY); //设置对象池回收标记 car.getComponent(CarControl).Init(carIndex.toString()); } //Car.ts //对象池回收标识符 private sign = null; Init(_sign) { this.sign = _sign; } onTriggerExit(other){ switch(other.owner.name){ case "bottomCollider": //从场景中移除自己 this.owner.removeSelf(); //回收 Laya.Pool.recover(this.sign,this.owner); break; } }
24.使用自定义字体
private txt_score; onAwake(){ this.txt_score = this.owner.getChildByName("txt_score"); Laya.loader.load("hemi head bd it.ttf",Laya.Handler.create(this,(font)=>{ this.txt_score.font = font.fontName; }),null,Laya.Loader.TTF); }
25.音乐音效一键静音
讯享网//静音 Laya.SoundManager.muted = true; //打开声音 Laya.SoundManager.muted = false;
26.时间轴动画---多状态切换
export default class BirdContr extends Laya.Script { constructor() { super(); } private rig = null; private ownBird =null; onAwake(): void { this.ownBird = this.owner; this.rig = this.owner.getComponent(Laya.RigidBody); Laya.stage.on(Laya.Event.CLICK,this,this.onMouseClick); } onMouseClick(): void { this.rig.linearVelocity = {x:0,y:-10}; this.ownBird.autoAnimation = "fly"; this.ownBird.loop = false; } onUpdate(){ if(this.ownBird.isPlaying==false){ this.ownBird.autoAnimation = "idle"; } } onTriggerEnter(other) { console.log(other.owner.name); switch (other.owner.name) { case "ground1": case "ground2": this.ownBird.autoAnimation = "die"; isGameOver = true; break; } } }
27.tween动画
讯享网showGameOver(){ this.overPanel.visible = true; //参数1:目标物体 参数2:目标属性 参数3:持续时间 参数4:动画类型 参数5:回调 --不需要可以不写 Laya.Tween.from(this.overPanel,{alpha:0},500,Laya.Ease.circIn,new Laya.Handler(this,()=>{ })); } onAwake(){ this.overPanel = this.owner.getChildByName("gameOver"); this.overPanel.getChildByName("btn_restart").on(Laya.Event.CLICK,this,()=>{ Laya.Tween.to(this.overPanel,{alpha:0},500,Laya.Ease.circIn,new Laya.Handler(this,()=>{ //this.overPanel.alpha = 0; this.overPanel.visible = false; this.init(); Laya.Scene.open("Main.json"); })); }); }
28.Dialog弹窗
关键字:详情
29.判断所在平台
if(Laya.Browser.onWeiXin){ //... }
30.数组
arrayA = ['bbb','ccc'];
push --- 在数组 后添加新数据。 arrayA.push('ddd'); // ['bbb','ccc','ddd']
unshift --- 在数组 前添加新数据。 arrayA.unshift('aaa'); //['aaa','bbb','ccc','ddd']
splice() --- 有两个参数时删除,否则是添加:
1.指定下标位置进行添加:
arrayA.splice(2,0,'mm',"nn"); // ['aaa','bbb','mm','nn','ccc','ddd']
2.指定下标位置进行删除:
arrayA.splice(1,2); //['aaa','nn','ccc','ddd']
pop() 删除掉最后的一个元素。 arrayA.pop(); // ['aaa','nn','ccc']
shift() 删除掉第一个元素。 arrayA.shift(); //['nn','ccc']
31.判断游戏是否在前台 ----防止游戏进入后台后update方法一直执行
讯享网Laya.stage.isVisibility
32.监听游戏是否失焦
Laya.stage.on(Laya.Event.BLUR,this,()=>{ ConstScript.updateStop = true; Laya.timer.scale = 0; }); Laya.stage.on(Laya.Event.FOCUS,this,()=>{ ConstScript.updateStop = false; Laya.timer.scale = 1; });

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容,请联系我们,一经查实,本站将立刻删除。
如需转载请保留出处:https://51itzy.com/kjqy/91296.html