Cocos---大作业:简单H5小游戏
Cocos大作业:传统美食分分类
知识点清单:
场景切换,监听时间,碰撞组件及回调,拖动角色移动,分数记录,随机数和定时器,背景音乐控制,资源池控制,预制体,进度条...
效果图展示#
游戏玩法如图所示
制作流程#
场景切换#
在按钮事件上
cc.director.loadScene('Play');
拖动物体#
挂载美食上即可
start () {
this.node.on('touchmove',this.func1,this);
}
func1(t){
let p = this.node.parent.convertToNodeSpaceAR(t.getLocation());
this.node.position=p;
}
音乐管理#
先构建如下#
挂载脚本在‘开关’上#
flag是用于检测开关的状态
@property(cc.Node)
kaiguan: cc.Node = null;
@property(cc.AudioClip)
bgAudio:cc.AudioClip=null;
audioID:number=0;
flag =false ;
protected onLoad(): void {
this.audioID=cc.audioEngine.play(this.bgAudio,true,0.5);
}
click(){
this.flag=!this.flag;
if(this.flag){
cc.audioEngine.pause(this.audioID);
this.kaiguan.getChildByName("关闭").active=true;
}
else {
cc.audioEngine.resume(this.audioID);
this.kaiguan.getChildByName("关闭").active=false;
}
}
碰撞检测#
必须先开启检测
需要提前输入目标名字
@property(String)
TargetName:string="1111";
// @property(cc.AudioClip)
// rightAudio:cc.AudioClip=null;
// dfs:string="dfasdf";
protected start(): void {
let manager = cc.director.getCollisionManager();
// 开启碰撞检测系统
manager.enabled = true;
}
onCollisionStay(other,self){
let b = other.world.aabb;
let a = self.world.aabb;//b中是否包含a
if(b.containsRect(a)&&other.node.name == this.TargetName){
console.log('ok');
MAIN.fenshu++;
// this.playRight();
this.node.destroy();
}
}
资源池#
预制体#
cc.Prefab 资源池:cc.NodePool
MAIN.pool2.put(newlibao);
bao=MAIN.pool2.get();
cc.NodePool API: 放入put(),获得get()
随机数:#
//介于1-3秒之间的随机数,发礼包的随机事件
// Math.floor(Math.random()*(max-min+1)+min);
if(this.rongqi.childrenCount>8)return ;
监听时间#
// 每0.5秒执行this.Food()函数
this.schedule(this.Food,0.5);
//10秒后执行over函数
this.scheduleOnce(this.over,11);
随机获取食物显示在盘子中#
Food(){
//介于1-3秒之间的随机数,发礼包的随机事件
// Math.floor(Math.random()*(max-min+1)+min);
if(this.rongqi.childrenCount>8)return ;
let suiji = Math.floor(Math.random()*(4-0+1)+0);
let bao = null;
if(suiji<1&&MAIN.pool1.size()>0)bao=MAIN.pool1.get();
else if(suiji<2&&MAIN.pool2.size()>0)bao=MAIN.pool2.get();
else if(suiji<3&&MAIN.pool3.size()>0)bao=MAIN.pool3.get();
else if(suiji<4&&MAIN.pool4.size()>0)bao=MAIN.pool4.get();
else return ;
if(MAIN.pool4.size()==0){
bao = cc.instantiate(this.yuebing);
}
//x坐标在-180到180之间随机
let randomX = Math.floor(Math.random()*(110+110+1)-110);
bao.position = cc.v3(randomX,-160,0);
this.rongqi.addChild(bao);
}
结束#
over(){
this.replay.active = true;
this.rongqi.destroy();
this.unscheduleAllCallbacks(); //取消所有定时器
}
更改分数#
update(t){
if(this.txt.string == MAIN.fenshu.toString())
return ;
else {
this.txt.string = MAIN.fenshu.toString();
cc.audioEngine.play( this.rightAudio,false,1);
}
}
分类:
Cocos学习
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 【杭电多校比赛记录】2025“钉耙编程”中国大学生算法设计春季联赛(1)