如何用CocosCreator实现射击小游戏

古城微笑少年丶 2022-10-15 00:42 242阅读 0赞

分析下制作步骤:

  1. 准备好资源,搭建场景
    资源的话可以自己到网上找,也可以直接用我的也行;创建好相应文件夹,把资源放到res文件夹下;

搭建场景:
第一步:创建一个单色精灵(Script) bg 背景, 设置好颜色,加一个Widget组件,使其充满屏幕;

第二步: 在bg节点下创建top和button空节点作为顶与底部,然后在两个空节点加入带刺的节点(直接将图片拖到top层级管理器就可以),现在我们需要给top与button节点添加一个Layout组件,属性设置如图,这样可以看到屏幕上下都有刺了。

第三步: 将玩家小人、子弹、敌机同样的方法加入到场景中,再创建一个Label节点用来显示分数,调节一下位置;

  1. 代码控制游戏
    第一步: 创建一个game脚本,挂载到dg节点上;

第二步: 编辑代码,在 properties添加属性,用来关联玩家、子弹、敌人节点,再编辑器关联;

第三步: 代码逻辑控制,包括初始化玩家、子弹、敌人;注册监听事件;写动作函数;计分判断等;

全部代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
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(“结束发射”);
}

});

发表评论

表情:
评论列表 (有 0 条评论,242人围观)

还没有评论,来说两句吧...

相关阅读