在ARFoundation中的AR相机和iOS相机之间切换

时间:2019-12-16 10:51:41

标签: ios unity3d

我在ARFoundation中有一个Unity3D项目,已使用this方法成功地将其嵌入到本机iOS项目中。

一旦Unity加载,我将在AR中增加3D模型,直到这一点一切正常。现在,我尝试在增强发生后使用UIImagePickerController从普通摄像机捕获视频。我能够从AR相机切换到iOS相机,但是当我尝试切换回Unity时,真实世界的跟踪会冻结。当我从ios摄像头切换回时,我希望真实世界的跟踪再次开始。有办法解决吗?

编辑:

我遵循了swift-unity GitHub,将unity项目嵌入iOS。我已经添加了GitHub页面中提到的所有必需文件。这些是我修改过的一些文件

我的AppDelgate

import UIKit

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

var window: UIWindow?

var application: UIApplication?

@objc var currentUnityController: UnityAppController!

var isUnityRunning = false

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
    // Override point for customization after application launch.

    self.application = application
    unity_init(CommandLine.argc, CommandLine.unsafeArgv)

    currentUnityController = UnityAppController()
    currentUnityController.application(application, didFinishLaunchingWithOptions: launchOptions)

    // first call to startUnity will do some init stuff, so just call it here and directly stop it again
    startUnity()
    stopUnity()

    return true
}

func applicationWillResignActive(_ application: UIApplication) {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.

    if isUnityRunning {
        currentUnityController.applicationWillResignActive(application)
    }
}

func applicationDidEnterBackground(_ application: UIApplication) {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.

    if isUnityRunning {
        currentUnityController.applicationDidEnterBackground(application)
    }
}

func applicationWillEnterForeground(_ application: UIApplication) {
    // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.

    if isUnityRunning {
        currentUnityController.applicationWillEnterForeground(application)
    }
}

func applicationDidBecomeActive(_ application: UIApplication) {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.

    if isUnityRunning {
        currentUnityController.applicationDidBecomeActive(application)
    }
}

func applicationWillTerminate(_ application: UIApplication) {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.

    if isUnityRunning {
        currentUnityController.applicationWillTerminate(application)
    }
}

func startUnity() {
    if !isUnityRunning {
        isUnityRunning = true
        currentUnityController.applicationDidBecomeActive(application!)
    }
}

func stopUnity() {
    if isUnityRunning {
        currentUnityController.applicationWillResignActive(application!)
        isUnityRunning = false
    }
}

}

UnityViewController

class ViewController: UIViewController {


override func viewDidLoad() {
    super.viewDidLoad()
    if let appDelegate = UIApplication.shared.delegate as? AppDelegate {
        appDelegate.startUnity()

        NotificationCenter.default.addObserver(self, selector: #selector(handleUnityReady), name: NSNotification.Name("UnityReady"), object: nil)
        NotificationCenter.default.addObserver(self, selector: #selector(handleUnityToggleRotation(_:)), name: NSNotification.Name("UnityToggleRotation"), object: nil)
    }
}

@objc func handleUnityReady() {
    showUnitySubView()
}



@IBAction func handleSwitchValueChanged(sender: UISwitch) {
    UnityPostMessage("NATIVE_BRIDGE", "StopCamera")
}

func showUnitySubView() {
    if let unityView = UnityGetGLView() {
        // insert subview at index 0 ensures unity view is behind current UI view
        view?.insertSubview(unityView, at: 0)

        unityView.translatesAutoresizingMaskIntoConstraints = false
        let views = ["view": unityView]
        let w = NSLayoutConstraint.constraints(withVisualFormat: "|-0-[view]-0-|", options: [], metrics: nil, views: views)
        let h = NSLayoutConstraint.constraints(withVisualFormat: "V:|-75-[view]-0-|", options: [], metrics: nil, views: views)
        view.addConstraints(w + h)
    }
}
    private func showPickerCamera(){if(UIImagePickerController.isSourceTypeAvailable(UIImagePickerController.SourceType.camera)){
        imagePicker.sourceType = .camera
        if viewModel.uploadType?.value == .videos {
            imagePicker.mediaTypes = [ kUTTypeMovie as String]
            imagePicker.cameraCaptureMode  = .video
            imagePicker.videoQuality = .typeMedium
        }else{
            imagePicker.mediaTypes = [ kUTTypeImage  as String]
            imagePicker.cameraCaptureMode  = .photo
        }

        imagePicker.allowsEditing = true
        imagePicker.modalPresentationStyle = .fullScreen

        self.present(imagePicker, animated: true, completion: nil)
    }
}
}

UnityUtils.mm

#include "RegisterMonoModules.h"
#include "RegisterFeatures.h"
 #include <csignal>
 static const int constsection = 0;

 void UnityInitTrampoline();

 extern "C" void unity_init(int argc, char* argv[])
 {
  @autoreleasepool
{
    UnityInitTrampoline();
    UnityInitRuntime(argc, argv);

    RegisterMonoModules();
    NSLog(@"-> registered mono modules %p\n", &constsection);
    RegisterFeatures();


    std::signal(SIGPIPE, SIG_IGN);
  }
}
 extern "C" void UnityPostMessage(NSString* gameObject, NSString* 
   methodName, NSString* message)
   {
  UnitySendMessage([gameObject UTF8String], [methodName UTF8String], 
 [message UTF8String]);
  }

0 个答案:

没有答案