ADL_Cocos_ChickenGame/assets/script/ClickEffect.ts
JZ 9a5bd987fc 01
初始文件
2024-10-11 18:09:54 +08:00

101 lines
3.3 KiB
TypeScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import { _decorator, Component, Node, EventTouch, tween, Vec3, UIOpacity, Color, Sprite, Label } from 'cc';
const { ccclass, property } = _decorator;
@ccclass('ClickEffect')
export class ClickEffect extends Component {
@property
public enableOpacityEffect: boolean = true; // 控制透明度效果的开关
private isClicked: boolean = false; // 点击后锁定状态
start() {
// 为节点添加触摸事件监听器
this.node.on(Node.EventType.TOUCH_START, this.onTouchStart, this);
this.node.on(Node.EventType.TOUCH_END, this.onTouchEnd, this);
this.node.on(Node.EventType.TOUCH_CANCEL, this.onTouchCancel, this);
// 初始化节点的透明度组件
if (!this.node.getComponent(UIOpacity)) {
this.node.addComponent(UIOpacity);
}
}
onTouchStart(event: EventTouch) {
if (this.isClicked) return; // 如果已经点击,不执行
// 点击时缩小节点
tween(this.node)
.to(0.1, { scale: new Vec3(0.9, 0.9, 0.9) })
.start();
// 仅在启用透明度效果时才进行透明度变化
if (this.enableOpacityEffect) {
// 更强烈的淡入效果,将透明度设置为 150部分透明
tween(this.node.getComponent(UIOpacity))
.to(0.1, { opacity: 150 })
.start();
}
}
onTouchEnd(event: EventTouch) {
if (this.isClicked) return; // 如果已经点击,不执行
// 还原节点大小
tween(this.node)
.to(0.1, { scale: new Vec3(1, 1, 1) })
.start();
// 仅在启用透明度效果时才恢复透明度
if (this.enableOpacityEffect) {
// 强烈的淡出效果,透明度还原为 255完全不透明
tween(this.node.getComponent(UIOpacity))
.to(0.1, { opacity: 255 })
.start();
}
// 获取 Sprite 组件并将节点变为灰色
const sprite = this.node.getComponent(Sprite);
if (sprite) {
sprite.color = new Color(128, 128, 128); // 设置节点为灰色
}
// 修改节点的 Label 文字为 "已领取"
const labelNode = this.node.getChildByName("Label");
if (labelNode) {
const label = labelNode.getComponent(Label);
if (label) {
label.string = "已领取";
}
}
// 设置为已点击状态,防止重复点击
this.isClicked = true;
console.log('节点被点击了,已领取');
}
onTouchCancel(event: EventTouch) {
if (this.isClicked) return; // 如果已经点击,不执行
// 当触摸被取消时,恢复大小
tween(this.node)
.to(0.1, { scale: new Vec3(1, 1, 1) })
.start();
// 仅在启用透明度效果时才恢复透明度
if (this.enableOpacityEffect) {
tween(this.node.getComponent(UIOpacity))
.to(0.1, { opacity: 255 })
.start();
}
}
onDestroy() {
// 移除事件监听,防止内存泄漏
this.node.off(Node.EventType.TOUCH_START, this.onTouchStart, this);
this.node.off(Node.EventType.TOUCH_END, this.onTouchEnd, this);
this.node.off(Node.EventType.TOUCH_CANCEL, this.onTouchCancel, this);
}
}