import GameComponent from "./GameComponent";
import GameObject from "./GameObject";
import PhycicsSystem from "./PhycicsSystem";
import Collider from "./Collider";
import MEvent from "../components/MEvent";

export default class Physics extends GameComponent {
    /**旋转速度 
     * @单位 （弧度制）度/帧
     * @方向 正值表示顺时针旋转，负表示逆时针旋转
     **/
    public rotateVelocity: number = 0;
    /**每帧速率的增量
     * x坐标表示对应坐标轴方向上速率的增量（标量）
     * @单位 像素/帧
     **/
    public acceleration: egret.Point = new egret.Point();
    /**速度 单位：像素/帧 */
    public velocity: egret.Point = new egret.Point();

    public get collider() {
        return this._collider;
    }
    public set collider(v: Collider) {
        this._collider = v;
        v.physics = this;
    }
    public _collider: Collider = null;

    public onMoved: (owner: GameObject) => void;

    public onFixedUpdate(dt: number) {
        this.velocity.x += this.acceleration.x * dt;
        this.velocity.y += this.acceleration.y * dt;
        this.owner.x += this.velocity.x * dt;
        this.owner.y += this.velocity.y * dt;

        this.onMoved && this.onMoved(this.owner);

        //旋转
        if (this.rotateVelocity != 0) {
            this.owner.rotation += this.rotateVelocity * dt;
        }
    }

    public moveTo(x: number | egret.Point, y?: number) {
        if (typeof x == "number") {
            if (!y) {
                console.error("invalid param");
                return;
            }
            this.owner.x = x;
            this.owner.y = y;
        } else {
            this.owner.x = x.x;
            this.owner.y = x.y;
        }

        this.onMoved && this.onMoved(this.owner);
    }

    protected onDisabled() {
        PhycicsSystem.instance.remove(this);
    }
    protected onEnabled() {
        PhycicsSystem.instance.add(this);
    }

    public onColliderResize(collider: Collider) {
        let center = collider.getCenter();
        this.owner.anchorOffsetX = center[0];
        this.owner.anchorOffsetY = center[1];
    }
}