import { _decorator, Component, Node, RigidBodyComponent, Vec3, math, ModelComponent, ColliderComponent, ICollisionEvent, Material } from "cc";
import { BtnEvent } from "./BtnEvent";
import LongTouchComponent from "./LongTouchComponent";
const { menu, ccclass, property } = _decorator;
@ccclass("PlayerCon")
@menu("physics/PlayerCon")
export class PlayerCon extends Component {
    @property({ type: Material })
    public purpleMat: Material = null;

    private rigidbody: RigidBodyComponent = null;
    private speed: number = 20;

    private startPos: Vec3 = null;
    private playerMaterial: ModelComponent;

    private gameOver:boolean=false;
    onLoad() {
        this.rigidbody = this.node.getComponent(RigidBodyComponent);
        this.startPos = this.node.getPosition();
        this.playerMaterial = this.node.getChildByName('Man').getComponent(ModelComponent);
    }

    start() {
        let Collider = this.getComponent(ColliderComponent);
        Collider.on('onCollisionStay', this.onCollision, this);
        this.gameOver=true;
    }

    update(dt) {
        if(this.gameOver){
            const position = this.node.getPosition();
            math.Vec3.scaleAndAdd(position, position, this.getDirection(0, 0, -1), dt * 30);
            this.node.setPosition(position);
        }else{
            this.gameInit();
            this.gameOver=true;
        }
    }


    gameInit(){
        this.node.setPosition(this.startPos);
        BtnEvent.matName="PurpleCube";
        BtnEvent.isone=true;
        this.playerMaterial.material=this.purpleMat;
        this.node.getChildByName('purpleSmoke').active=true;
        this.node.getChildByName('yellowSmoke').active=false;
    }

    private onCollision(event: ICollisionEvent) {
        /**如果按了不能再按 */
        LongTouchComponent._isTouching = false;
        LongTouchComponent._isDoubleJump = false;

        /**判断碰到的颜色是否一致 */
        if (event.otherCollider.node.name != BtnEvent.matName) {
            this.gameOver=false;
            console.log(this.node.getPosition());
        }
    }

    getDirection(x, y, z) {
        const result = new Vec3(x, y, z);
        math.Vec3.transformQuat(result, result, this.node.getRotation());
        return result;
    }
}
