分析下制作步驟:
1. 準備好資源,搭建場景
資源的話可以自己到網上找,也可以直接用我的也行;創建好相應文件夾,把資源放到res文件夾下;
搭建場景:
第一步:創建一個單色精靈(Script) bg 背景, 設置好顏色,加一個Widget組件,使其充滿屏幕;
第二步: 在bg
節點下創建top
和button
空節點作為頂與底部,然后在兩個空節點加入帶刺的節點(直接將圖片拖到top層級管理器就可以),現在我們需要給top與button
節點添加一個Layout組件
,屬性設置如圖,這樣可以看到屏幕上下都有刺了。
第三步: 將玩家小人、子彈、敵機同樣的方法加入到場景中,再創建一個Label節點用來顯示分數,調節一下位置;
2. 代碼控制游戲
第一步: 創建一個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實現射擊小游戲的詳細內容,更多關于CocosCreator實現射擊小游戲的資料請關注服務器之家其它相關文章!
原文鏈接:https://blog.csdn.net/qq_45021180/article/details/104347037