Unity血条超出屏幕

如果超出屏幕 拉回屏幕内

// 拉回屏幕内
Vector2 position = Vector2.zero   // 屏幕坐标
var viewportPos = Camera.main.WorldToViewportPoint(entityOffsetPos);
if (viewportPos.z > 0)
{
    if (viewportPos.x < 0 && viewportPos.y >= 0 && viewportPos.y <= 1)
    {
        position.x = -Screen.currentResolution.width * 0.5f;
        position.x += Screen.currentResolution.width * 0.05f;
    }
    if (viewportPos.x > 1 && viewportPos.y >= 0 && viewportPos.y <= 1)
    {
        position.x = Screen.currentResolution.width * 0.5f;
        position.x -= Screen.currentResolution.width * 0.05f;
    }
    if (viewportPos.y < 0 && viewportPos.x >= 0 && viewportPos.x <= 1)
    {
        position.y = -Screen.currentResolution.height * 0.5f;
        position.y += Screen.currentResolution.height * 0.05f;
    }
    if (viewportPos.y > 1 && viewportPos.x >= 0 && viewportPos.x <= 1)
    {
        position.y = Screen.currentResolution.height * 0.5f;
        position.y -= Screen.currentResolution.height * 0.05f;
    }
}

检测视椎体是否包含物体

// 是否在摄像机视椎体内
public static bool IsObjectVisible(Camera cam, Vector3 pos)
{
    bool isVisable = true;
    Vector3 viewPos = cam.WorldToViewportPoint(pos);
    if (viewPos.x >= 0 && viewPos.x <= 1 && viewPos.y >= 0 && viewPos.y <= 1 && viewPos.z > 0)
    {
        // Your object is in the range of the camera, you can apply your behaviour
        isVisable = true;
    }
    else
    {
        isVisable = false;
    }
    return isVisable;
}
发布了258 篇原创文章 · 获赞 45 · 访问量 22万+

猜你喜欢

转载自blog.csdn.net/A13155283231/article/details/103786932