这篇文章主要介绍怎么使用CocosCreator实现射击小游戏,文中介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们一定要看完!
资源的话可以自己到网上找,也可以直接用我的也行;创建好相应文件夹,把资源放到res文件夹下;
搭建场景:
第一步:创建一个单色精灵(Script) bg 背景, 设置好颜色,加一个Widget组件,使其充满屏幕;
第二步: 在bg
节点下创建top
和button
空节点作为顶与底部,然后在两个空节点加入带刺的节点(直接将图片拖到top层级管理器就可以),现在我们需要给top与button
节点添加一个Layout组件
,属性设置如图,这样可以看到屏幕上下都有刺了。
第三步: 将玩家小人、子弹、敌机同样的方法加入到场景中,再创建一个Label节点用来显示分数,调节一下位置;
第一步: 创建一个game
脚本,挂载到dg
节点上;
第二步: 编辑代码,在 properties
添加属性,用来关联玩家、子弹、敌人节点,再编辑器关联;
第三步: 代码逻辑控制,包括初始化玩家、子弹、敌人;注册监听事件;写动作函数;计分判断等;
全部代码:
cc.Class({
extends: cc.Component,
properties: {
playerNode: cc.Node,
enemyNode: cc.Node,
fireNode: cc.Node,
scoreNode: cc.Label,
},
onLoad () {
this.playLoad();
this.fireLoad();
this.enemyLoad();
this.node.on("touchstart",this.fire,this);
},
update (dt) {
if(Math.abs(this.fireNode.y-this.enemyNode.y)<(this.fireNode.height/3+this.enemyNode.height/3)
&&Math.abs(this.fireNode.x-this.enemyNode.x)<(this.fireNode.width/3+this.enemyNode.width/3)){
console.log("击败敌机");
this.scoreNode.string= ++this.score;//击中得分
this.fireNode.stopAction(this.fireAction);
this.enemyNode.stopAction(this.enemyAction);
this.enemyNode.active=false;
this.fireNode.active=false;
this.fireLoad();//初始化子弹
this.enemyLoad();// 初始化敌机
}
},
// 关闭事件监听
onDestroy(){
this.node.off("touchstart",this.fire,this);
},
// 初始玩家
playLoad(){
this.score=0;
this.playerNode.y=-cc.winSize.height/4;
},
//初始化子弹
fireLoad(){
this.fireNode.active=true;
this.isFire=false;
this.fireNode.x=this.playerNode.x;
this.fireNode.y=this.playerNode.y+this.playerNode.height;
},
// 初始化敌机
enemyLoad(){
this.enemyNode.active=true;
this.enemyNode.x=Math.random()* cc.winSize.width;
this.enemyNode.y=cc.winSize.height/3;
let x=cc.winSize.width/2-this.enemyNode.width/2;
let y=Math.random()* cc.winSize.height/4;
let seq=cc.repeatForever(cc.sequence(cc.moveTo(1.5,cc.v2(-x,y)),cc.moveTo(1.5,cc.v2(x,y))));
this.enemyAction=this.enemyNode.runAction(seq);
},
// 死亡 重新加载游戏
dear(){
console.log("死亡");
cc.director.loadScene("game_scenes");
},
// 发射子弹
fire(){
if(this.isFire) return;
this.isFire=true;
console.log("开始发射");
var fireaction=cc.sequence(
cc.moveTo(1,cc.v2(this.playerNode.x,cc.winSize.height/2)),
cc.callFunc(()=>{
this.dear();
}));
this.fireAction=this.fireNode.runAction(fireaction);
console.log("结束发射");
}
});
以上是“怎么使用CocosCreator实现射击小游戏”这篇文章的所有内容,感谢各位的阅读!希望分享的内容对大家有帮助,更多相关知识,欢迎关注亿速云行业资讯频道!
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。