当前位置: 代码迷 >> 综合 >> 只将unity的UI控件添加到iOS视图层,不显示unity的原生背景(二)
  详细解决方案

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

热度:17   发布时间:2023-10-31 05:05:38.0

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

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

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

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

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

- (BOOL)pointInside:(CGPoint)point withEvent:(UIEvent *)event
{//判断一下渲染API是否为metal,OpenGLES暂未实现if(UnitySelectedRenderingAPI() == apiMetal){// 获取渲染surfaceUnityDisplaySurfaceMTL* 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;// 得到上一次渲染的TextureMTLTextureRef 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的视图了。