import { _decorator, Component, js,Node, PhysicsRayResult } from 'cc';
import { GunBase } from './GunBase';
import { PoolManager } from '../../core/manager/PoolManager';
import { Enemy } from '../../game/Enemy';
import { ResUtil } from '../../utils/ResUtil';

const { ccclass, property } = _decorator;

@ccclass('BulletBase')
export class BulletBase extends Component {
    public isDead: boolean = false;
    //枪的数据 在gunBase中
    public gunBase: GunBase = null!;
    //子弹自动回收的时间3s
    public recycleTime: number = 3;
    
    constructor(){
        super();
        this.isDead = false;
    }
    
    start() {
        this.scheduleOnce(this.autoRecycle.bind(this),this.recycleTime);
    }

    /**
     * 加入射击中的效果
     * @param e 碰撞到的结果
     */
    public addHitImpact(e:PhysicsRayResult) {
        ResUtil.loadRes("enemy/sundries/hit_impact", this.node)
            .then((impact: Node | null) => {
                if(impact){
                   impact.worldPosition = e.hitPoint.add(e.hitNormal.multiplyScalar(0.01));
                   impact.forward = e.hitNormal.multiplyScalar(-1);
                   impact.setParent(e.collider.node,true);
                }
                this.scheduleOnce(()=>{
                    if(impact.parent){
                       PoolManager.putNode(impact);
                    }
                },3);
            })
            .catch((error: Error) => {
                console.error("加载sundries/hit_impact异常", error);
            });
    }
    
    /**
     * 自动回收子弹
     */
    public autoRecycle(){
        if(!this.isDead){
            this.isDead = true;
            PoolManager.putNode(this.node);
        }
    }
}

