前言:
我前面幾篇文章都是CocosCreator的基礎知識,這裏做一個實戰遊戲並不是說我們的基礎知識都學完了,其實還有一部分。不過前面的知識佔據了大部分,我們已經能夠製作一些小型的遊戲來練練手了,下面就簡單的介紹一些這一款小遊戲的製作,由於難度係數不大,所有基本在一個小時之內就能夠完成,這是在你有前面基礎的條件下哦。
項目的源文件下載鏈接:https://download.csdn.net/download/qq_45021180/12161933
源碼文件我上傳在csdn了,免費下載不需要任何積分與C幣!
先看一下最後的效果吧
分析下製作步驟:
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("結束髮射");
}
});
如果有遊戲開發大佬看到,考慮帶帶筆者,謝謝;
如果有新人對遊戲開發感興趣,可以一起學習;