我試圖在SceneKit中重新編碼相機管理。爲此,我使用UIPanGestureRecognizer圍繞一個物體(在這種情況下圍繞場景的中心)旋轉相機。SceneKit父節點旋轉期間子節點位置未更改
接着我得到的不同的比或長度,以確定的角度在其中相機安裝假想球體(cameraOrbit在代碼)的軸(X,Y,Z)添加。
我的問題是,我用相機的位置來確定的角度在球添加。但是這個位置是不變的。當我改變球體旋轉時,子節點相機的位置永遠不會更新。那麼角度永不改變。
import SceneKit
import UIKit
class SceneManager
{
private let scene: SCNScene
private let view: SCNView
private let camera: SCNNode
private let cameraOrbit: SCNNode
private let cameraRadius: Float
init(view: SCNView, assetFolder: String, sceneName: String, cameraName: String, backgroundColor: UIColor) {
self.view = view
self.scene = SCNScene(named: (assetFolder + "/" + sceneName))!
if (self.scene.rootNode.childNodeWithName(cameraName, recursively: true) == nil) {
print("Fatal error: Cannot find camera in scene with name :\"", cameraName, "\"")
exit(1)
}
self.camera = self.scene.rootNode.childNodeWithName(cameraName, recursively: true)! // Retrieve cameraNode created in scene file
self.cameraOrbit = SCNNode()
self.cameraOrbit.addChildNode(self.camera)
self.cameraRadius = sqrt(pow((self.camera.position.x), 2) + pow(self.camera.position.y, 2)) // CameraOrbit radius for rotation camera in panHandler
self.scene.rootNode.addChildNode(self.cameraOrbit)
let panGesture = UIPanGestureRecognizer(target: self, action: #selector(panHandler(_:)))
panGesture.maximumNumberOfTouches = 1
self.view.addGestureRecognizer(panGesture)
self.view.backgroundColor = backgroundColor
self.view.pointOfView = self.camera
self.view.scene = self.scene
}
@objc private func panHandler(sender: UIPanGestureRecognizer) {
let alpha = cos(self.camera.position.z/self.cameraRadius) // Get angle of camera
// --
print(self.camera.position) // <-------- (X, Y, Z) The axes position are always the same
// --
var ratioX = 1 - ((CGFloat)(alpha)/(CGFloat)(M_PI)) // Get the radio with angle for apply to Z and X axes rotation
var ratioZ = ((CGFloat)(alpha)/(CGFloat)(M_PI))
// Change direction of rotation depending camera's position in trigonometric circle
if (self.camera.position.z > 0 && self.camera.position.x < 0) {
ratioZ *= -1
} else if (self.camera.position.z < 0 && self.camera.position.x < 0) {
ratioX *= -1
ratioZ *= -1
} else if (self.camera.position.z > 0 && self.camera.position.x > 0) {
ratioX *= -1
}
// Set the angle rotation to add at imaginary sphere (cameraOrbit)
let xAngleToAdd = (sender.velocityInView(sender.view!).y/10000) * ratioX
let yAngleToAdd = (sender.velocityInView(sender.view!).x/10000) * (-1)
let zAngleToAdd = (sender.velocityInView(sender.view!).y/10000) * ratioZ
let rotation = SCNAction.rotateByX(xAngleToAdd, y: yAngleToAdd, z: zAngleToAdd, duration: 0.5)
self.cameraOrbit.runAction(rotation)
}
}
如果有人有想法?由於
我注意到你提及「cameranode」從'self.rootNode.childNodeWithName'。然後調用'self.camearOrbit.addChildNode(self.cameranode)'。在將cameranode添加到cameraOrbit之前,你沒有叫'self.cameranode.removeFromParentNode'嗎? –
我會盡力處理父母/子女的財產並回復你。感謝 – Ynamy