Last active
August 17, 2025 13:08
-
-
Save nickyeh97/e2d1abc77af7e1d10a7127478f7079c3 to your computer and use it in GitHub Desktop.
生成一個帶有動畫的爆炸效果,3 秒後自動清除
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { _decorator, Component, EventTouch, instantiate, Node, Prefab, Animation as CCAnimation, UITransform, Vec3, AnimationClip } from 'cc'; | |
const { ccclass, property } = _decorator; | |
@ccclass('TapExplosion') | |
export class TapExplosion extends Component { | |
@property(Prefab) | |
explosionPrefab: Prefab = null; | |
@property(AnimationClip) | |
explosionClip: AnimationClip = null; | |
@property(Node) | |
tapArea: Node = null; | |
onLoad() { | |
this.tapArea && this.tapArea.on(Node.EventType.TOUCH_END, this.onClick, this); | |
} | |
onDestroy() { | |
this.tapArea && this.tapArea.off(Node.EventType.TOUCH_END, this.onClick, this); | |
} | |
private onClick(event: EventTouch) { | |
if (!this.explosionPrefab || !this.tapArea) return; | |
const uiPos = event.getUILocation(); | |
const uiTrans = this.tapArea.getComponent(UITransform); | |
if (!uiTrans) return; | |
const localPos = uiTrans.convertToNodeSpaceAR(new Vec3(uiPos.x, uiPos.y, 0)); | |
this.spawnBoom(localPos, this.tapArea); | |
} | |
private spawnBoom(localPos: Vec3, parent: Node) { | |
const boom: Node = instantiate(this.explosionPrefab); | |
parent.addChild(boom); | |
boom.setPosition(localPos); | |
let anim = boom.getComponent(CCAnimation); | |
if (!anim) anim = boom.addComponent(CCAnimation); | |
if (this.explosionClip) { | |
anim.defaultClip = this.explosionClip; | |
anim.play(this.explosionClip.name); | |
} | |
this.scheduleOnce(() => boom.isValid && boom.destroy(), 3); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment