const { ccclass, property } = cc._decorator;

@ccclass
export default class Test extends cc.Component {

    private wid2 = 1136 / 2;
    private hei2 = 640 / 2;
    private r: number = 32;
    private left: number = -this.wid2 + this.r;
    private right: number = this.wid2 - this.r;
    private bottom: number = -this.hei2 + this.r;
    private top: number = this.hei2 - this.r;
    private v0: number = 10;
    private vx: number;
    private vy: number;
    private rad: number;

    private ball: cc.Node;

    protected start(): void {
        this.ball = this.node.getChildByName("ball");
        this.rad = 0;
        this.vx = Math.cos(this.rad) * this.v0;
        this.vy = Math.sin(this.rad) * this.v0;
    }

    private addRad(): void {
        this.rad = (this.rad + Math.PI * 2 / 10) % (Math.PI * 2);
        this.vx = Math.cos(this.rad) * this.v0;
        this.vy = Math.sin(this.rad) * this.v0;
    }

    protected update(): void {
        this.ball.x += this.vx;
        this.ball.y += this.vy;
        if (this.vx < 0) {
            if (this.ball.x <= this.left) {
                this.ball.x = this.left;
                this.addRad();
            }
        } else {
            if (this.ball.x >= this.right) {
                this.ball.x = this.right;
                this.addRad();
            }
        }
        if (this.vy < 0) {
            if (this.ball.y <= this.bottom) {
                this.ball.y = this.bottom;
                this.addRad();
            }
        } else {
            if (this.ball.y >= this.top) {
                this.ball.y = this.top;
                this.addRad();
            }
        }
    }

}
