import { _decorator, Component, Node, Prefab, instantiate, EventTouch, UITransform, Vec3, v3, RigidBody2D, math, Camera, PhysicsSystem2D, EPhysics2DDrawFlags, v2 } from "cc";
const { ccclass, property } = _decorator;

@ccclass("Editor")
export class Editor extends Component {
  @property(Camera)
  camera: Camera = null;

  @property(Node)
  map: Node = null;

  onLoad() {
    const system = PhysicsSystem2D.instance;
    system.enable = true;
    system.debugDrawFlags = EPhysics2DDrawFlags.Aabb | EPhysics2DDrawFlags.Pair | EPhysics2DDrawFlags.CenterOfMass | EPhysics2DDrawFlags.Joint | EPhysics2DDrawFlags.Shape;
    system.gravity = v2(system.gravity.multiplyScalar(2));

    // 物理步长，默认 fixedTimeStep 是 1/60
    system.fixedTimeStep = 1 / 30;

    // 每次更新物理系统处理速度的迭代次数，默认为 10
    system.velocityIterations = 8;

    // 每次更新物理系统处理位置的迭代次数，默认为 10
    system.positionIterations = 8;

    this.map.on(
      Node.EventType.TOUCH_MOVE,
      (e: EventTouch) => {
        let curPos = v3(e.getLocation().x, e.getLocation().y);
        this.camera.screenToWorld(curPos, curPos);
        this.map.parent.getComponent(UITransform).convertToNodeSpaceAR(curPos, curPos);
        let prePos = v3(e.getPreviousLocation().x, e.getPreviousLocation().y);
        this.camera.screenToWorld(prePos, prePos);
        this.map.parent.getComponent(UITransform).convertToNodeSpaceAR(prePos, prePos);
        let cross = curPos.cross(prePos);
        if (cross.z > 0) {
          //顺时针
          this.map.angle -= e.getDelta().length() / 4;
        } else if (cross.z < 0) {
          //逆时针
          this.map.angle += e.getDelta().length() / 4;
        }
        // this.map.children.forEach((node) => {
        //   node.getComponent(RigidBody2D)["_body"].syncPositionToPhysics(false); //位置
        //   node.getComponent(RigidBody2D)["_body"].syncRotationToPhysics(false); //旋转
        // });
        system.physicsWorld.syncSceneToPhysics();
      },
      this
    );
  }
}
