When I was developing a 2D game, I found a problem about the hierarchy when two role overlap, whitch role should on top?

the best way to resolve the problem is using sortingorder in sprite.

//chartransform为角色的transform组件
        float yPos = chartransform.position.y;
        //spriterenderer为角色的Sprite Renderer组件
        //通过改变sortingorder来确定gameobject在sortinglayer中的order in layer
        //因为y轴越大层级越靠后,所以给结果前加一个负数
        //scale用来扩大y轴数据映射在层级上的影响,根据游戏中实际使用的素材尺度来确定,取100 1000都可以
        spriterenderer.sortingOrder = -Mathf.RoundToInt(yPos * scale);

add codes above in game process script's method of Update. It will caculate sortingOrder regarding role every frame base on the value of Y position.

image.png

打赏
支付宝 微信
上一篇 下一篇