物体层级显示问题

目的:当角色在物体前面时,角色优先渲染;当角色在物体后面时,物体优先渲染
图示:

角色优先渲染

角色优先

物体优先渲染

物体优先
原理:修改sorting layer的order

代码思路

角色和物体设置在同一sorting layer,角色order设置为0,物体设置为-1或1来实现是否优先渲染。
采用 Physics2D.BoxCastAll来判定角色是否在物体前面,在前面时物体order设置为-1,反之设置为1。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class OrderSwitch : MonoBehaviour
{

Vector3 pos;//物体position
public Vector3 offset;//boxcast检测范围相对position的偏移
public Vector3 size;//boxcast检测范围大小
public LayerMask playerLayer;//角色所在层级(boxcast检测的层级)
public bool isDraw;//是否在开启debug.drawline,方便在scene窗口调试offset和size
private void Start()
{
pos = transform.position;
}
private void Update()
{
if (BoxCheck(pos,offset,size,playerLayer,isDraw)!=null)
{
GetComponent<SpriteRenderer>().sortingOrder = 1;
}
else
{
GetComponent<SpriteRenderer>().sortingOrder = -1;
}
}
public Collider2D BoxCheck(Vector3 originPos, Vector3 offset, Vector2 size, int layer, bool isDraw)
{

if (isDraw)
{
Debug.DrawLine(originPos + offset + new Vector3(-size.x / 2, -size.y / 2, 0), originPos + offset + new Vector3(size.x / 2, -size.y / 2, 0), Color.green);
Debug.DrawLine(originPos + offset + new Vector3(-size.x / 2, -size.y / 2, 0), originPos + offset + new Vector3(-size.x / 2, size.y / 2, 0), Color.green);
Debug.DrawLine(originPos + offset + new Vector3(size.x / 2, size.y / 2, 0), originPos + offset + new Vector3(size.x / 2, -size.y / 2, 0), Color.green);
Debug.DrawLine(originPos + offset + new Vector3(size.x / 2, size.y / 2, 0), originPos + offset + new Vector3(-size.x / 2, size.y / 2, 0), Color.green);
}

RaycastHit2D[] hit = Physics2D.BoxCastAll(originPos + offset, size, 0, Vector2.zero, 0, layer);
if (hit != null && hit.Length > 0)
{
return hit[0].collider;
}
else
{
return null;
}
}
}