import { Component, instantiate, Node, UITransform, Vec3, view, _decorator } from 'cc';
const { ccclass, property } = _decorator;

@ccclass('ReelEffect')
export class ReelEffect extends Component {

    speed: number = 15;

    moutainNode1: Node;
    moutainNode2: Node;

    moutainTf: UITransform;
    posXOut: number;
    tempPos: Vec3 = new Vec3();

    onLoad() {
        this.moutainNode1 = this.node.children[0];

        this.moutainNode2 = instantiate(this.moutainNode1);
        this.moutainNode2.parent = this.node;

        this.moutainTf = this.moutainNode1.getComponent(UITransform);

        this.moutainNode1.getPosition(this.tempPos);
        this.tempPos.x = this.tempPos.x - this.moutainTf.width;
        this.moutainNode2.setPosition(this.tempPos);

        this.posXOut = view.getVisibleSize().width * 0.5 + this.moutainTf.width * 0.5;

    }

    addPosX(node: Node, dx: number) {
        node.getPosition(this.tempPos);
        this.tempPos.x += dx;
        node.setPosition(this.tempPos);
    }

    update(dt: number) {
        let dx = dt * this.speed;
        this.addPosX(this.moutainNode1, dx);
        this.addPosX(this.moutainNode2, dx);

        this.moutainNode1.getPosition(this.tempPos);
        if (this.tempPos.x > this.posXOut) {
            this.moutainNode2.getPosition(this.tempPos);
            this.tempPos.x = this.tempPos.x - this.moutainTf.width;
            this.moutainNode1.setPosition(this.tempPos);
        }

        this.moutainNode2.getPosition(this.tempPos);
        if (this.tempPos.x > this.posXOut) {
            this.moutainNode1.getPosition(this.tempPos);
            this.tempPos.x = this.tempPos.x - this.moutainTf.width;
            this.moutainNode2.setPosition(this.tempPos);
        }
    }
}

