import { _decorator, Animation, AnimationClip, BoxCollider2D, Collider2D, Component, Contact2DType, ICollisionEvent, IPhysics2DContact, Node, PhysicsSystem2D, SpriteFrame, UITransform } from 'cc'; import { Tools } from '../../Tools/Tools'; import { LifeBar } from './LifeBar'; const { ccclass, property } = _decorator; @ccclass('Bullet') export class Bullet extends Component { explodeframes: SpriteFrame[] = []; bulletFrames: SpriteFrame[] = []; explodeAni: Animation = null; bulletAni: Animation = null; //是否爆炸 true -> 爆炸 isExplode: boolean = false; //子弹速度 bulletSpeed: number = 100; //子弹方向 direction: number = 1; //攻击力 atk: number = null; //被攻击的节点 targetNode: Node = null; //是否碰撞 private _hasCollided: boolean = false; protected onLoad(): void { const collider = this.getComponent(Collider2D); if (collider) { //collider.on(Contact2DType.BEGIN_CONTACT, this._onBeginContact, this) } } start() { this.explodeAni = Tools.createAnimation(this.explodeframes, 5, this.node, AnimationClip.WrapMode.Normal); this.bulletAni = Tools.createAnimation(this.bulletFrames, 5, this.node, AnimationClip.WrapMode.Loop); //this.node.setPosition(0, 0, 0); this.setState(false); } setState(isExplode: boolean) { if (isExplode) { this.bulletSpeed = 0; this.explodeAni.play(); this.explodeAni.once(Animation.EventType.FINISHED, () => { this.node.destroy() }, this.node) } else { this.bulletAni.play(); } } _onBeginContact(otherCollider: BoxCollider2D) { const lifeBar = this.targetNode.getComponent(LifeBar); lifeBar.updateProgressBar(lifeBar._curHp - this.atk); this.setState(true); } update(deltaTime: number) { this.move(deltaTime); this.onBulletCollision(this.targetNode); } move(dt: number) { let x = this.node.getWorldPosition().x; let y = this.node.getWorldPosition().y; let z = this.node.getWorldPosition().z; if (this.direction) { x = x + this.bulletSpeed * dt; } else { x = x - this.bulletSpeed * dt; } this.node.setWorldPosition(x, y, z) } // 处理子弹碰撞 onBulletCollision(targetNode: Node) { if(this._hasCollided) return; if(!targetNode.isValid) return; const boxBullet = this.node.getComponent(UITransform).getBoundingBoxToWorld(); const boxTarget = targetNode.getComponent(UITransform).getBoundingBoxToWorld(); if (boxTarget.containsRect(boxBullet)) { const targetLifeBar = targetNode.getComponent(LifeBar); if((targetLifeBar._curHp - this.atk) <= 0){ this.targetNode.destroy(); this.node.destroy(); } targetLifeBar.updateProgressBar(targetLifeBar._curHp - this.atk); this._hasCollided = true; this.setState(true); } } //targetNode为目标节点,子弹需要攻击的对象 //如果子弹与targetNode碰撞,targetNode的hp(血量)将会减少子弹发射者的atk(攻击力); //同时子弹播放爆炸动画,播放结束后,子弹销毁 }