返回

打破常规,合成大西瓜:Cocos实战全攻略

前端

Cocos合成大西瓜案例——下

在上一节中,我们完成了游戏的开始页面,现在让我们深入游戏主界面,探索合成的乐趣。

😜游戏主界面

经过前两节的学习,我们已经掌握了游戏的主体框架,现在是时候进入游戏内容了。

实践过程

1. 分析玩法

页面的右上方显示玩家的当前关卡、最高得分和当前得分。

2. 创建界面

在界面中放置背景图片,并在上面添加一个容器节点,用于放置游戏元素。

// 创建背景图片
const background = new cc.Sprite('res/bg.png');
this.node.addChild(background);

// 创建容器节点
const gameContainer = new cc.Node();
this.node.addChild(gameContainer);

3. 生成水果

我们通过随机生成位置和类型来创建水果。

// 生成水果
for (let i = 0; i < 5; i++) {
  const fruit = new cc.Sprite('res/apple.png');
  fruit.setPosition(cc.randomRange(0, this.node.width), cc.randomRange(0, this.node.height));
  gameContainer.addChild(fruit);
}

4. 合成水果

当两个相同类型的水果碰撞时,它们会合成一个更大的水果。

// 添加碰撞事件
fruit1.on('collision-enter', function (other) {
  if (fruit1.type === other.type) {
    // 合成水果
    const newFruit = new cc.Sprite('res/banana.png');
    newFruit.setPosition(fruit1.getPosition());
    gameContainer.addChild(newFruit);
    // 销毁原始水果
    fruit1.destroy();
    other.destroy();
  }
});

5. 胜利条件

当场上只存在一个大西瓜时,玩家获胜。

// 判断胜利条件
if (gameContainer.children.length === 1 && gameContainer.children[0].name === 'watermelon') {
  // 胜利
}

总结

通过这节内容,我们完成了游戏主界面的制作。接下来,我们将探索更多高级玩法,让游戏更加精彩!