// Learn TypeScript:
//  - [Chinese] https://docs.cocos.com/creator/manual/zh/scripting/typescript.html
//  - [English] http://www.cocos2d-x.org/docs/creator/manual/en/scripting/typescript.html
// Learn Attribute:
//  - [Chinese] https://docs.cocos.com/creator/manual/zh/scripting/reference/attributes.html
//  - [English] http://www.cocos2d-x.org/docs/creator/manual/en/scripting/reference/attributes.html
// Learn life-cycle callbacks:
//  - [Chinese] https://docs.cocos.com/creator/manual/zh/scripting/life-cycle-callbacks.html
//  - [English] http://www.cocos2d-x.org/docs/creator/manual/en/scripting/life-cycle-callbacks.html

const { ccclass, property } = cc._decorator;

@ccclass
export default class Line extends cc.Component {


    private body: any = null
    private canUpDate: boolean = false;

    onLoad(): void {
        this.init();
    }

    onDestroy(): void {

    }


    public init(): void {

        // let gravity = new b2Vec2(0, -10);    //重力值
        // this.world = new b2World(gravity, true);

        var position = this.node.position;
        let width = this.node.width;
        let height = this.node.height;

        var bd = new b2BodyDef();
        bd.angle = -this.node.angle * Math.PI / 180;
        bd.position = this.convertToPWorld(position);
        bd.gravityScale = 0.5;
        this.body = window.world.CreateBody(bd);
        var shape = new b2PolygonShape();
        shape.SetAsBoxXY(width / 32 / 2, height / 32 / 2);
        this.body.CreateFixtureFromShape(shape, 0.1);

        this.scheduleOnce(() => { this.canUpDate = true }, .8)
    }

    private convertToPWorld(pos): any {
        return new b2Vec2(pos.x / 32, pos.y / 32);
    }

    private convertToNode(worldPoint) {
        let leftUpPos = cc.v2(worldPoint).mul(32);
        let leftDownPos = cc.v2(leftUpPos.x, leftUpPos.y);
        return leftDownPos;
    }

    update(dt) {
        if (!this.canUpDate) return;
        this.node.position = this.convertToNode(this.body.GetPosition());
        this.node.angle = -this.body.GetAngle() / Math.PI / 180;
    }
}
