import { _decorator, Vec3,Node } from 'cc';
import { PoolManager } from '../../core/manager/PoolManager';
import { Game } from '../../game/Game';
import { BulletBase } from '../base/BulletBase';
import { GunBase } from '../base/GunBase';
const { ccclass, property } = _decorator;

//敌人1006 坦克 所用子弹
@ccclass('Bullet14')
export class Bullet14 extends BulletBase {
    //射击方向的位置
    private vector: Vec3 = null;
    //是否击中玩家
    private isHit: boolean = false;
    //根据子弹速度计算出移动的时间
    private moveTime: number = 0;
    //当前时间
    private curTime: number = 0;

    /**
     * 初始化一个子弹
     * @param gun 属于哪把枪
     */
    public init(gun:GunBase){
        //13.6 距离大概在13.6
        const factor: number = 50;
        const distance:number = Vec3.distance(gun.muzzleNode.worldPosition.clone(), Game.I.player.head.worldPosition.clone());
        //这儿是为了保障子弹最短运行时间 不会小于自动回收子弹的时间 就能保证如果要命中的时候 100%命中 并且扣扣血
        this.moveTime = Math.min(distance * factor / gun.data.bulletSpeed, this.recycleTime - 0.01);
        this.curTime = 0.0;
        this.gunBase = gun;
        this.isDead = false;
    }

    /**
     * 设置子弹开始位置和射击方向
     * @param isHit 是否必中
     * @param v 射向的方向
     */
    public setBulletVector(v: Vec3,isHit: boolean){
        this.isHit = isHit;
        const bulletSpeed = this.gunBase.data.bulletSpeed;
        this.vector = v.clone().multiplyScalar(bulletSpeed);
        this.node.forward = v;
    }

    /**
     * 射击速度发生改变
     */
    public speedChange() {
        const bulletSpeed = this.gunBase.data.bulletSpeed;
        if(this.vector) {
           this.vector = this.vector.normalize().multiplyScalar(bulletSpeed);
        }
    }
    /**
     * 实时帧更新
     */
    public update(deltaTime: number) {
        if(Game.I.isGameOver 
            || Game.I.isPause) {
            this.isDead = true;
            PoolManager.putNode(this.node);
            return;
        }
        if(this.vector) {
            this.curTime += deltaTime;
            const moveDelta = this.vector.clone().multiplyScalar(deltaTime); 
            this.node.worldPosition = this.node.worldPosition.add(moveDelta);
            //如果时间超过了移动时间 就回收
            if(this.curTime >= this.moveTime && this.isHit) {
               Game.I.player.subHP(this.gunBase.data.attack, this.gunBase.data);
               this.autoRecycle();
               this.curTime = 0.0;
            }
        }
    }
}