
import { _decorator, Component, RigidBody, Collider, v3, MeshRenderer, MeshCollider, CCObject, Vec2, Vec3 } from 'cc';
import { GameNode } from './GameNode';
import { Main } from './Main';
const { ccclass, property } = _decorator;

@ccclass('TileItem')
export class TileItem extends Component {
    static TileItem: any;

    auto_rotation = false;
    collider: Collider[] = [];
    rigid: RigidBody = null;
    removed:boolean=false
    removedPos:Vec3//消除的时候做一个向中间靠拢的动画
    playRmovedEff:boolean=false

    private static starttime = Date.now();
    private static getY() {
        let n = Date.now() - this.starttime;
        return n / 10;
    }
    start() {
        this.collider = this.node.children[0].getComponents(Collider);
    }

    //禁用碰撞
    _enableCollider: boolean = false;
    set enableCollider(b) {
        let worldRotation = this.node.children[0].worldRotation.clone();
        this.node.worldPosition = this.node.children[0].worldPosition.clone();
        this.node.children[0].position = v3();
        this.node.children[0].worldRotation = worldRotation;
        this.rigid.useGravity = b;
        // this.collider.enabled = b;
        // this.rigid.enabled = b;
    }

    get enableCollider() {
        return this._enableCollider;
    }

    destoryCollider() {
        this.node.children[0].position = v3();
        this.node.children[0].eulerAngles = v3()
        this.collider.map(a => a.enabled = false)
        this.rigid.destroy();
    }

    
    addCollider(): RigidBody {
        let _render = this.node.children[0].getComponent(MeshRenderer);
        this.rigid = _render.node.addComponent(RigidBody);
        this.collider.map(a => a.enabled = true)
        return this.rigid;
    }

   
    update() {
        if(this.auto_rotation) {
           this.node.setRotationFromEuler(0, TileItem.getY(), 0);
        }
        if(this.rigid.isValid){
            /*let plate = Main._instance._GameNode.plate;
            const gooseWorldPos = this.node.worldPosition;
            const plateWorldPos = plate.worldPosition;
            // 检测是否超出盘子范围（示例：XZ 平面限制）
            const maxX = 2, maxZ = 2; // 盘子半径
            if (Math.abs(gooseWorldPos.x - plateWorldPos.x) > maxX || 
                Math.abs(gooseWorldPos.z - plateWorldPos.z) > maxZ) {
                // 施加反向力（推回盘子中心）
                const forceDir = new Vec3(
                    plateWorldPos.x - gooseWorldPos.x,
                    0,
                    plateWorldPos.z - gooseWorldPos.z
                ).normalize().multiplyScalar(10); // 力的大小
                this.rigid.applyForce(forceDir);
            }*/
        }
    }
}

