
import { _decorator, Component, Node, Prefab, RigidBody2D, v2, macro, UITransform, Vec3, v3, Vec2, AudioSourceComponent, } from 'cc';
import { GameMgr } from './GameMgr';
import { ObjPool } from './ObjPool';
const { ccclass, property } = _decorator;

let outV3 = v3();

@ccclass('Rocket')
export class Rocket extends Component {

    @property({
        type: Prefab
    })
    bulletPrefab: Prefab;

    @property({
        type: Node
    })
    rocketSprite: Node;

    @property({
        type: Node
    })
    shootPoint: Node;

    @property
    speed: number = 10;

    velocity: Vec2 = v2();

    audio: AudioSourceComponent;

    onLoad() {
        this.audio = this.getComponent(AudioSourceComponent);
    }


    shoot(heading: Vec3) {
        this.velocity.x = heading.x * this.speed;
        this.velocity.y = heading.y * this.speed;

        let pos = this.shootPoint.getComponent(UITransform).convertToWorldSpaceAR(Vec3.ZERO, outV3);
        let bullet = ObjPool.getNode(this.bulletPrefab.data.name, this.bulletPrefab);
        bullet.parent = GameMgr.inst.gameLayer;
        bullet.parent.getComponent(UITransform).convertToNodeSpaceAR(pos, outV3);
        bullet.setPosition(outV3);
        bullet.angle = this.node.angle;

        let rb2d = bullet.getComponent(RigidBody2D);
        rb2d.fixedRotation = true;
        rb2d.linearVelocity = this.velocity;

        this.audio.play();
    }
}