添加游戏控制脚本
添加了一个Game脚本来添加计分、游戏失败和重新开始的相关逻辑。
// Game.js
properties: {
// 这个属性引用了星星预制资源
starPrefab: {
default: null,
type: cc.Prefab
},
// 星星产生后消失时间的随机范围
maxStarDuration: 0,
minStarDuration: 0,
// 地面节点,用于确定星星生成的高度
ground: {
default: null,
type: cc.Node
},
// player 节点,用于获取主角弹跳的高度,和控制主角行动开关
player: {
default: null,
type: cc.Node
}
},
保存脚本后将 Game 组件添加到 层级管理器 中的 Canvas 节点上(选中 Canvas 节点后,拖拽脚本到 属性检查器 上,或者点击 属性检查器 的 添加组件 按钮,并从 添加用户脚本组件 中选择 Game。)
把之前的星星资源添加到 Game 组件的 Star Prefab 属性中。。。
然后设置 Min Star Duration 和 Max Star Duration 属性的值为 3 和 5,星星生成和消失的时间。
在随机位置生成星星
接下来我们继续修改 Game 脚本,在 onLoad 方法 后面 添加生成星星的逻辑:
// Game.js
onLoad: function () {
// 获取地平面的 y 轴坐标
this.groundY = this.ground.y + this.ground.height/2;
// 生成一个新的星星
this.spawnNewStar();
},
spawnNewStar: function() {
// 使用给定的模板在场景中生成一个新节点
var newStar = cc.instantiate(this.starPrefab);
// 将新增的节点添加到 Canvas 节点下面
this.node.addChild(newStar);
// 为星星设置一个随机位置
newStar.setPosition(this.getNewStarPosition());
},
getNewStarPosition: function () {
var randX = 0;
// 根据地平面位置和主角跳跃高度,随机得到一个星星的 y 坐标
var randY = this.groundY + Math.random() * this.player.getComponent('Player').jumpHeight + 50;
// 根据屏幕宽度,随机得到一个星星 x 坐标
var maxX = this.node.width/2;
randX = (Math.random() - 0.5) * 2 * maxX;
// 返回星星坐标
return cc.v2(randX, randY);
},