Cocos Creator2D游戏开发(15)---预制体和按钮的绑定以及冷却效果的实现
场景: 植物大战僵尸中,种植植物前,要判断状态,只有在阳光充足时才能点击
图片资源:

- 预制体的创建,创建一个空节点命名: CardTemplate,将三张豌豆射手相关的图片拖入 如下图

其中card_mask图片中的透明度改为150;
- 在assets中创建prefab文件夹,将CardTemplate节点直接拖入prefab文件夹,然后就出现了CardTemplate预制体

- 双击预制体CardTemplate,创建脚本CardTemplate,并将脚本CardTemplate拖入右侧属性检查器中;

- 在脚本CardTemplate中添加代码
import { _decorator, Component, Node, Sprite } from 'cc';
const { ccclass, property } = _decorator;@ccclass('CardTemplate')
export class CardTemplate extends Component {@property({ type: Node })public cardLight: Node = null; // 卡牌亮节点@property({ type: Node })public cardGrey: Node = null; // 卡牌暗节点@property({ type: Sprite })public cardMask: Sprite = null; // 卡牌遮罩start() {this.cardLight.active = true;this.cardGrey.active = false;this.cardMask.node.active = false;}update(deltaTime: number) {}onButtonClick(){console.log("按钮被点击了")}}
-
节点对应绑定,拖过去一一对应

-
在card_light下,添加button组件
ClickEvents改为1, 第二个框选择CardTemplate,第三个框选择onButtonClick

点击运行,尝试点击豌豆射手,就可以看到控制台打印的日志了;
调整下面三行的值,再次点击测试;
this.cardLight.active = true;this.cardGrey.active = false;this.cardMask.node.active = false;
- 冷却效果的实现
图片card_mask属性调整

添加代码:
import { _decorator, Component, Node, Sprite } from 'cc';
const { ccclass, property } = _decorator;@ccclass('CardTemplate')
export class CardTemplate extends Component {@property({ type: Node })public cardLight: Node = null; // 卡牌亮节点@property({ type: Node })public cardGrey: Node = null; // 卡牌暗节点@property({ type: Sprite })public cardMask: Sprite = null; // 卡牌遮罩@property({ type: Number })private cdTime: number = 5; // 卡牌冷却时间private cdTimer: number = 0; // 卡牌冷却计时器start() {this.cardLight.active = false;this.cardGrey.active = true;this.cardMask.node.active = true;this.cdTimer = this.cdTime}update(deltaTime: number) {if(this.cdTimer >0 ){this.cdTimer -= deltaTime;this.cardMask.fillRange = -(this.cdTimer / this.cdTime);if(this.cardMask.fillRange >0){this.cardLight.active = true;this.cardGrey.active = false;this.cardMask.node.active = false;}}}onButtonClick(){console.log("按钮被点击了")this.cardLight.active = false;this.cardGrey.active = true;this.cardMask.node.active = true;this.cdTimer = this.cdTime}}
效果如下

知识点来源: https://www.bilibili.com/video/BV1AQe9eqEfw/
