cocos繪制隨機形狀

//繪制形狀 dotCount:頂點數
    draw () {
        this.getComponent(cc.RigidBody).gravityScale=0
        this.node.position.x=360
        this.node.position.y=640

        const dotCount = Math.round(Math.random()*6+3);
        const points = [];
        let vectors =[];

        //隨機形狀
        const dig = 2 * Math.PI / dotCount;//周長2πr 一周的弧度數為2πr/r=2π,
        for (let i = 0; i < dotCount; i++)
        {
            const side = Math.random()*300+ 50;

            //頂點
            const x = side * Math.cos(i * dig);//cos=x/side
            const y = side * Math.sin(i * dig);//sin=y/side
            points.push({x:Math.round(x),y:Math.round(y)});

            let v = cc.v2(Math.round(x), Math.round(y));
            vectors.push(v);
        }
        cc.warn(points);
        cc.warn(vectors);

        //添加碰撞盒
        this.getComponent(cc.PhysicsPolygonCollider).points=vectors;

        //繪制
        const ctx = this.getComponent(cc.Graphics);
        ctx.clear();
        const len = points.length;
        ctx.moveTo(points[len - 1].x, points[len - 1].y);
        for (let i = 0; i < points.length; i++) {
            ctx.lineTo(points[i].x, points[i].y);
        }
        ctx.fill();
        ctx.stroke();
    }
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容