import SwiftUI
import RealityKit
import AVFoundation //视频播放需要用到avfoundation
struct ContentView : View {
var body: some View {
return ARViewContainer().edgesIgnoringSafeArea(.all)
}
}
struct ARViewContainer: UIViewRepresentable {
//实现目标:在垂直面墙体上放置一个tv。
//动作:点击电视,电视开始播放视频文件
func updateUIView(_ uiView: ARView, context: Context) {}
func makeUIView(context: Context) -> ARView {
let arView = ARView(frame: .zero)
//定义一个电视,包括1外壳和2屏幕部分(播放视频)
let dimensions:SIMD3<Float>=[1.25,0.05,0.6]
//屏幕整体,以米做单位定义长宽高
//houshing外壳部分:
let housingMesh = MeshResource.generateBox(size: dimensions)
let housingMat = SimpleMaterial(color:.blue,roughness:0.2,isMetallic:true)
//📺外壳材质,黑色,粗糙程度0.2,材质为金属
let housingEntity = ModelEntity(mesh:housingMesh,materials:[housingMat])
//建立外壳实体
//screen显示区域部分:
let screenMesh = MeshResource.generatePlane(width:dimensions.x, depth:dimensions.z )
let screenMat = SimpleMaterial( color:.black, roughness:0.1, isMetallic: false)
//显示区域部分尺寸,屏幕材质,注意,屏幕显示没有厚度
let screenEntity = ModelEntity(mesh:screenMesh,materials:[screenMat])
//显示屏实体
screenEntity.name = "tvScreen"
//显示屏部分给个名字,方便下方动作调用
housingEntity.addChild(screenEntity)
//实体合成,将屏幕外壳与屏幕显示部分结合到一起,方便调用
screenEntity.setPosition([0,(dimensions.y)/2+0.01,0],relativeTo:housingEntity)
//稍微分离屏幕显示和屏幕边框部分,显示出外壳和显示屏的凹陷感
//在arview添加扫描点
let anchor = AnchorEntity(plane:.vertical)
//建立垂直锚点
anchor.addChild(housingEntity)
//生成屏幕模型
arView.scene.addAnchor(anchor)
//让电视支持点击手势操作
arView.enableTapGesture()
housingEntity.generateCollisionShapes(recursive:true)
return arView
}
}
//定义动作
extension ARView{
//定义手势识别器
func enableTapGesture(){
let tapGestureRecognizer = UITapGestureRecognizer(target:self,action:#selector(handleTap(recognize:)))
self.addGestureRecognizer(tapGestureRecognizer)
//使用默认动作
}
//确认点击的是tv
@objc func handleTap(recognize:UITapGestureRecognizer){
let tapLocation = recognize.location(in:self)
if let entity = self.entity(at: tapLocation) as? ModelEntity,entity.name == "tvScreen"{
//播放视频,调用AVfoundation
loadVideoMaterial(for:entity)
}
}
func loadVideoMaterial(for entity: ModelEntity) {
let asset = AVAsset(url:Bundle.main.url(forResource:"video1",withExtension:"mp4")!)
let playerItem = AVPlayerItem(asset:asset)
let player = AVPlayer()
entity.model? .materials = [VideoMaterial(avPlayer: player)]
player.replaceCurrentItem(with: playerItem)
player.play()
}
}
搜了很多资料,let anchor = AnchorEntity(plane:[.vertical,.horizontal]),可我使用都不行,求大佬解答