只将unity的UI控件添加到iOS视图层,不显示unity的原生背景(二)

刚面试完,信心备受打击,项目经验不够就是容易受歧视。

继续更新吧。。。把自己这几个月学的分享一下

上一篇博客实现了将unity的相机背景改为透明的,能够显示出iOS的视图。

但是这时候,我们只能操作显示出来的iOS视图,不能点击unity的控件,那我们怎么才能实现点击呢?

在unityView.mm中,我们添加代码

- (BOOL)pointInside:(CGPoint)point withEvent:(UIEvent *)event
{
    //判断一下渲染API是否为metal,OpenGLES暂未实现
    if(UnitySelectedRenderingAPI() == apiMetal)
    {
        // 获取渲染surface
        UnityDisplaySurfaceMTL* surf = (UnityDisplaySurfaceMTL*)GetMainDisplaySurface();
        // 渲染surface尺寸
        CGSize s = ((CAMetalLayer*)self.layer).drawableSize;
        // 得到点击坐标
        CGPoint p = [self convertPoint:point toView:self];
        
        // 坐标转换
        CGFloat bw = self.bounds.size.width;
        CGFloat bh = self.bounds.size.height;
        CGFloat box = self.bounds.origin.x;
        CGFloat boy = self.bounds.origin.y;
        CGFloat x = (p.x - box)/bw * s.width;
        CGFloat y = (p.y - boy)/bh * s.height;
        
        // 得到上一次渲染的Texture
        MTLTextureRef lastTex = surf->lastSystemColorRB;
        // 获取Texture中此坐标的颜色值
        MTLRegion region = MTLRegionMake2D(x, y, 1, 1);
        Byte byteBuff[4];
        [lastTex getBytes:byteBuff bytesPerRow:_surfaceSize.width*4 fromRegion:region mipmapLevel:0];
        // 判断Alpha值
        int a = byteBuff[3];
        if(a > 0 )
        {
            return YES;
        }
        else
        {
            return NO;
        }
    }
    return YES;
}


Classes/Unity/UnityRendering.h中的UnityDisplaySurfaceMTL结构声明中,添加
OBJC_OBJECT_PTR MTLTextureRef lastSystemColorRB,用来保存上一帧渲染Texture。

// Metal display surface
START_STRUCT(UnityDisplaySurfaceMTL, UnityDisplaySurfaceBase)
    OBJC_OBJECT_PTR CAMetalLayer* layer;
    OBJC_OBJECT_PTR MTLDeviceRef device;

    OBJC_OBJECT_PTR MTLCommandQueueRef commandQueue;
    OBJC_OBJECT_PTR CAMetalDrawableRef drawable;

    OBJC_OBJECT_PTR MTLTextureRef systemColorRB;
    OBJC_OBJECT_PTR MTLTextureRef targetColorRT;
    OBJC_OBJECT_PTR MTLTextureRef targetAAColorRT;

    OBJC_OBJECT_PTR MTLTextureRef depthRB;
    OBJC_OBJECT_PTR MTLTextureRef stencilRB;

    unsigned colorFormat; // [MTLPixelFormat]
    unsigned depthFormat; // [MTLPixelFormat]

    // add here
    OBJC_OBJECT_PTR MTLTextureRef lastSystemColorRB;
END_STRUCT(UnityDisplaySurfaceMTL)

在每次渲染前保存lastSystemColorRB。修改Classes/Unity/MetalHelper.mm的StartFrameRenderingMTL函数
在 surface->systemColorRB = [surface->drawable texture] 后面添加
surface->lastSystemColorRB = surface->systemColorRB。

这样就可以实现,既能点击unity的控件,又能点击iOS的视图了。





  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 5
    评论
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值