import Ball from "./Ball";
import Gun from "./Gun";

export default class World extends p2.World {
    material: p2.Material;//碰撞时的弹性变化
    _skin: egret.DisplayObjectContainer;
    gun: Gun;
    constructor(options?: any) {
        super(options);
        this.init();
    }

    protected onHitBegin(evt): void {
        var ball: Ball;
        if (evt.bodyA instanceof Ball) ball = evt.bodyA;
        if (evt.bodyB instanceof Ball) ball = evt.bodyB;
        if (ball && ball.mass == 0) {
            ball.setImpulse = true;//可以设置给小球冲量
            ball.mass = 200;
        }

        if (ball && ball.setImpulse) {
            const vec = this.gun.vec;
            ball.applyImpulse([vec.x * 2, vec.y], [0, 0]);
            ball.setImpulse = false;
        }
    }

    /** 
     * 设置刚体碰撞的弹性
     * */
    setMaterial(body1: p2.Body, body2: p2.Body): void {
        body1.shapes[0].material = this.material;
        body2.shapes[0].material = this.material;
        var roleAndStoneMaterial = new p2.ContactMaterial(
            this.material, this.material,
            { restitution: 0.7, friction: 0 });//弹性，摩擦力
        this.addContactMaterial(roleAndStoneMaterial);
    }

    loop(): any {
        this.bodies.forEach(body => {
            if (body instanceof Ball) {
                body.updateSkin();
            }
        });
    }

    init() {
        this.gravity = [0, 200];
        this.material = new p2.Material(0);
        this.on("beginContact", this.onHitBegin.bind(this));
    }

    set skin(val: egret.DisplayObjectContainer) { this._skin = val }
    get skin() { return this._skin }
}