Untiy 程序生成一个扇形sprite

发表于2019-01-23
评论0 2.4k浏览
类似王者荣耀中近程职业与远程职业攻击范围是不同的,类似这种扇形的检测范围是根据什么来实现的呢?多数情况下还是需要策划同学来自行配置来控制扇形的范围。这才有了本篇要和大家分享的使用程序来成成扇形检测范围的纹理。

直接给出代码:
    /// <summary>
    /// Generates the sprite.
    /// </summary>
    /// <param name="sr">SpriteRenderer.</param>
    /// <param name="size">扇形的半径.</param>
    /// <param name="range">扇形的展开范围(角度).</param>
    /// <param name="sectorColor">颜色.</param>
    void GenerateSprite(SpriteRenderer sr, float size, float range,Color sectorColor) {
        float radius = size / 2;
        Texture2D t = new Texture2D((int)size,(int)size);
        Vector2 center = new Vector2(radius, 0);
        for (int w = 0; w < size; w++){  
            for (int h = 0; h < size; h ++){
                Color c;
                Vector2 v = new Vector2(w, h) - center;
                float alpha = 0f;
                float angle = GameCommon.GetAngle(Vector2.zero ,v);
                float dis = Vector2.Distance(v, Vector2.zero);
                if(angle > 90-range/2 && angle < 90 + range / 2 &&
                   dis > 20){
                    float rate = dis / size;
                    alpha = Mathf.Min(0.8f - rate*rate*rate,1);
                    if( Mathf.Abs(angle - (90 - range / 2)) < 1 || 
                       Mathf.Abs(angle - (90 + range / 2)) < 1){
                        alpha += 0.5f;
                    }
                    c = sectorColor * alpha * 0.8f;
                }else{
                    c = new Color(0, 0, 0, 0);
                }
                t.SetPixel(w,h,c);  
            }  
        }  
        t.Apply();  
        Sprite pic = Sprite.Create(t, new Rect(0, 0, size, size), new Vector2(0.5f, -0.2f));  
        sr.sprite = pic;  
    } 

实现效果如下:

如社区发表内容存在侵权行为,您可以点击这里查看侵权投诉指引