import { _decorator, Component, instantiate, Node, Prefab, Vec3 } from "cc";

const { ccclass, property } = _decorator;


class SnakeNode {

    node: Node = null;
    next: SnakeNode = null;

}

const _tempPos = new Vec3();
const _tempPrePos = new Vec3();

@ccclass("Snake1")
export class Snake1 extends Component {

    @property(Prefab)
    nodePrefab: Prefab = null;

    @property
    gap: number = 50;

    head: SnakeNode = null;
    last: SnakeNode = null;

    onLoad() {
        this.last = this.head = new SnakeNode();
        this.head.node = this.node;

    }

    addNode() {
        const node = instantiate(this.nodePrefab);
        this.node.parent.addChild(node);
        node.position = this.last.node.position;

        const snakeNode = new SnakeNode();
        snakeNode.node = node;
        this.last.next = snakeNode;
        this.last = snakeNode;

    }

    update(dt: number) {
        let pre: SnakeNode = this.head;
        let current: SnakeNode = this.head.next;
        while (current) {
            const posDir = current.node.getPosition(_tempPos)
                .subtract(pre.node.position)
                .normalize();

            const pos = pre.node.getPosition(_tempPrePos)
                .add(posDir.multiplyScalar(this.gap));
            current.node.setPosition(pos);

            pre = current;
            current = current.next;
        }
    }
}