0
我是0123,的新手,我試圖製作一個相對簡單的應用程序,在其中創建「牆」並且用戶「向其拋擲」球,並且它會反彈回來。SceneKit物理在ARKit中無法正常工作
我創建壁作爲SCNPlane
其中用戶正指向照相機像這樣:
private func createWall(withPosition position: SCNVector3) -> SCNNode {
let wallGeometry = SCNPlane(width: 0.3, height: 0.3)
wallGeometry.firstMaterial?.isDoubleSided = true
wallGeometry.firstMaterial?.diffuse.contents = UIColor.green.withAlphaComponent(0.7)
let parentNode = SCNNode(geometry: wallGeometry)
let (position, _) = cameraPosition()
parentNode.position = position
parentNode.physicsBody = SCNPhysicsBody(type: .static, shape: SCNPhysicsShape(geometry: wallGeometry, options: nil))
parentNode.physicsBody?.isAffectedByGravity = false
self.wall = parentNode
return parentNode
}
我得到的方向和攝像機的位置與此功能:
cameraPosition()
:
func cameraPosition() -> (SCNVector3, SCNVector3) {
guard let frame = sceneView.session.currentFrame else { return (SCNVector3(0, 0, -1), (SCNVector3(0, 0, 0))) }
let matrix = SCNMatrix4(frame.camera.transform)
let direction = SCNVector3(-matrix.m31, -matrix.m32, -matrix.m33)
let location = SCNVector3(matrix.m41, matrix.m42, matrix.m43)
return ((location + direction), direction)
}
// Helper function
func +(left: SCNVector3, right: SCNVector3) -> SCNVector3 {
return SCNVector3(left.x + right.x, left.y + right.y, left.z + right.z)
}
我創建了Ball()
的實例並拋出它們,如下所示:
let (position, direction) = cameraPosition()
// throw ball
let ball = Ball()
ball.position = position //SCNVector3(0,0,0)
sceneView.scene.rootNode.addChildNode(ball)
let impulseModifier = Float(10)
ball.physicsBody!.applyForce(SCNVector3(direction.x*impulseModifier, direction.y*impulseModifier, direction.z*impulseModifier), asImpulse: true)
的球類:
class Ball: SCNNode {
override init() {
super.init()
let sphere = SCNSphere(radius: 0.05)
sphere.firstMaterial?.diffuse.contents = UIColor.red
self.geometry = sphere
self.physicsBody = SCNPhysicsBody(type: .dynamic, shape: SCNPhysicsShape(geometry: sphere, options: nil))
}
}
的問題是,很多時候,而不是皮球竟然打在牆上,它只是通過它旅行,彷彿物理學體功能不正常。我注意到,當我改變攝像機和牆壁之間的距離和角度時,有時它會更好,但結果從未像我嘗試過的那樣一致。
我也嘗試將牆位置更改爲:SCNVector3(0, 0, -1)
,將其置於距離世界原點1米的深處,結果稍好,但仍不一致。
問題出現在哪裏,爲什麼?
在此先感謝!
您是否設法解決這個問題? –
@mike_t還不幸:/ – Eilon